Transcript Slide 1

Character Functions
ctype.h library
getchar/putchar
– getchar()
• reads a character from standard input
• returns the value of the character
• ch = getchar()  scanf(“%c”, &ch)
– putchar(char ch)
• prints the character argument onto standard output
• putchar(ch)  printf(“%c”, ch)
Dr. Sadık Eşmelioğlu
CENG 114
2
ctype.h library
#include <ctype.h>
Function
Value
isalpha(char )
T if a-z or A-Z
isdigit(char)
T if 0-9
islower(char)
T if a-z
isupper(char)
T if A-Z
ispunct(char)
T if punctuation (not a control character, not a space, not an
alphabetical char, and not a digit
isspace(char)
T if white space (space, tab, new line)
tolower(char)
returns lowercase
toupper(char)
returns uppercase
Dr. Sadık Eşmelioğlu
CENG 114
3
Example
• Write a function that takes a string argument and converts it
to all uppercase letters
void CnvUppr(char *str)
{
int i = 0;
while(str[i] != '\0') {
if(islower(str[i]))
str[i] = toupper(str[i]);
i++;
}
}
Dr. Sadık Eşmelioğlu
CENG 114
4
Example
• Write a program that will read a sentence from stdin and
search for dangerous words.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
result = strtok(str1, delims);
while(result != NULL) {
n = SearchWrd(result);
if(n > 0) printf("%s is found\n", result);
result = strtok(NULL, delims);
}
void CnvUppr(char *str);
int SearchWrd(char *Wrd);
int main(void) {
char str1[80];
int n;
char *result;
char *delims = " ,.!?";
Dr. Sadık Eşmelioğlu
return(0);
}
CENG 114
5
Example
void CnvUppr(char *str)
{
int i = 0;
while(str[i] != '\0') {
if(islower(str[i]))
str[i] = toupper(str[i]);
i++;
}
int SearchWrd(char *Wrd)
{
char *WrdLst[2] = {"BOMB", "GUN"};
int i;
int Found = 0;
for(i = 0; i < 2; i++)
if(strcmp(Wrd, WrdLst[i]) == 0) {
Found=1;
break;
}
}
return(Found);
}
Dr. Sadık Eşmelioğlu
CENG 114
6