Pages

Monday, November 23, 2009

Using character functions with strings

Although character functions are meant to be used with character but with the clever use of logic they can be effectivly used with strings also. To use a character function with a string we wil have to split the string into characters and then apply these functions. When a string is converted to individual characters the character function then can access all these character one by one and perform the desired operation.


Example 1: Finding out number of alphabets, digits and symbols in a given string
#include
#include
void main()
{
char str[40];
int letters=0,numbers=0,symbols=0,i,l;
printf(“\nEnter a sentence (max 40 characters) : “);
gets(str);
l=strlen(str);
for(i=0;i {
If(isalpha(str[i])
letters++;
else if(isdigit(str[i])
numbers++;
else
symbols++;
}
printf(“\nNo. Of alphabets : %d”,letters);
printf(“\nNo. Of digits : %d”,numbers);
printf(“\nNo. Of symbols : %d”,symbols);
}


Example 2: Finding out number of spaces and words in a given string.
#include
#include
int i,spaces=0;
void main()
{
char line[20];
printf(“\nEnter a string : “);
gets(line);
for(i=0;i{
if(isspace(line[i]))
spaces++;
}

printf(“\nSpaces %d”,spaces);
printf(“\nWords %d”,spaces+1);
}

0 comments:

Post a Comment