Reputation: 17
I have to do this excercise and I'm really trying to do my best, but I can't figure out how to solve it.
It says I need to code a program to analyze a string. And it needs to give the numbers of words and numbers.
Note that a number is also a word. 123 is a word and a number, but for example 4HIMATE is not a number, only a word.
I'll let my code of what I got so far
int main()
{
int size= 256;
char s[256]= "Hi 123 Peter 8hi hi8";
char space[]= " ";
int wordCount= 0;
int numberCount= 0;
strcat(s, space);
strlwr(s);
for(int i= 0; s[i]!='\0'; i++)
{
if(s[i+1]== ' ' && s[i]>96 && s[i]<123)
{
wordCount++;
}
if(s[i+1]== ' ' && s[i]>47 && s[i]<58)
{
wordCount++;
}
}
for (int j=0; j<size; j++)
{
if(s[j+1]== ' ' && s[j]>47 && s[j]<58)
{
numberCount++;
}
}
printf("Words= %d\n", wordCount);
printf("Numbers= %d", numberCount);
return 0;
}
My output needs to be=
Words= 5 Numbers= 1
But the mistake is on numbers, the output is 2.
I don't really know how to solve that, so I need some help.
Corrected some mistakes (edit):
for(int i= 0; s[i]!='\0'; i++)
{
if(s[i+1]== ' ' && s[i]>'a' && s[i]<'z')
{
wordCount++;
}
if(s[i+1]== ' ' && s[i]>'0' && s[i]<'9')
{
wordCount++;
}
}
for (int j=0; s[j]!='\0'; j++)
{
if(s[j+1]== ' ' && s[j]>'0' && s[j]<'9')
{
numberCount++;
}
}
Upvotes: 0
Views: 354
Reputation: 409482
Your logic is flawed, as you won't be counting the last "word" (hi8
) as a word. Similarly you won't count "numbers" if they are last in the string. This could be found out through some debugging.
One possible solution is to use states. One state that tells if you are in a word or not, and another state that tells if the current word is all digits or not.
Using states, when looping over the string you check if the current character is an alpha-numeric character. If it is, and the is-a-word state is not set then set that state. When changing the state, then also check if the current character is a digit and if it is then set the is-number state. Continuing the loop, if is-a-word state is set, and the current character is not a digit, then you clear the is-number state. When reaching something that is a space then you check your states: If is-a-word is set, then clear it and increase the word counter; If is-number state is set, then increase the number counter and clear the state.
In pseudo code it could be something like this:
is-a-word-state = false
is-a-number-state = false
for each character in string
{
if (current-character is alphanumeric and is-a-word-state == false)
{
// Started a new word
is-a-word-state = true
if (current-character is digit)
{
// Could be a number
is-a-number-state = true
}
}
if (current-character is not digit)
{
// Current word (if any) is not a number
is-a-number-state = false
}
if (current-character is space)
{
if (is-a-word-state == true)
{
// End of the current word
word-counter++
if (is-a-number-state == true)
{
// Word is a number
number-counter++
}
}
is-a-word-state = false
is-a-number-state = false
}
}
Upvotes: 1