Count Characters, Count Words, Search for specific String.
Hi everybody,
I'm new to C and I'm trying to find out every function with Help, but this time it was of no use. So I just need a tip or something like this for this three questions !!!
I'm using in my programm the <string.h>, <stdio.h> header files and if possible I want to stay with those header files.
The %s input is taken with gets for two strings.
and now to my problems:
1. How can I count characters (also considering lowercase and uppercase [islower ?? isupper ??])
i.g.: Input String 1: Ive got a fast car
Input String 2: Its a Ferrari
Character to search: a
First String: 3 times found
Second String: 2 times found
2. How can I count the words in the String ?
i.g.: Same strings as above
1st String: 5 Words
2nd String: 3 Words
3. How can I search for a specific word in a String ? (there is a command for searching only one specific char in the begining and in the end of the string (as seen on the Help Examples) , but I couldn't find one which is for searching Words !!)
i.g.: Same strings as above
Phrase to Search: Ferrari
First String: Not Found
Second String: Found
4. As some DOS users may remember there was a 'pause' command which could be used in BAT files is there a opposite command for C/C++ ???
with my best regards
Client
Re: Count Characters, Count Words, Search for specific String.
Question 1
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *lines[] = {"I have a fast car", "Its a Ferrari"};
char LookFor = 'a';
char *ptr;
int count, i;
for (i = 0; i < 2; i++)
{
count = 0;
ptr = lines[i];
while ((ptr = strchr(ptr, LookFor)) != NULL)
{
count++; ptr++;
}
printf("letter %c found %d times in line %d\n", LookFor, count, i+1);
}
return (0);
}
Question 2
Look through each string, counting the number of characters that are deemed to split words. This is not always just the spaces, it could be commas, full stops, exclamation marks etc etc. The choice is yours!
Question 3
Use the function strstr(); Look that one up in the book, it's easy to use.
Question 4
Read this faq page