I am a beginner programmer and there was this exercise I found that said.
Write a string of characters and determine the number of words, numbers, uppercase and lowercase characters and spaces.
I thought what I build was a decent enough program and it works, kinda!
The problem is that when I try to run it the result is not entirely correct.
For example; When I write: HI MY name is Ani 1 1 2 a
it says that
Spaces=8 correct here
Numbers= 3 correct here as well
Upper Case characters=4 It should be 5
Lower Case characters = 7 it should be 9
Words = 26 which is completely wrong
As for the words, I found a new way to count them. By counting spaces 1
but I want to count them correctly
Is it possible to point out the mistakes?
This is what I have done so far
int main() {
char str[1000 1];
int words = 0;
int numbers = 0;
int uppercharacters = 0;
int lowercharacters = 0;
int spaces = 0;
int i;
printf("Please enter the string of characters: ");
gets(str);
for (i = 0; str[i] != '\0'; i ) {
if (str[i] > 'a' && str[i] < 'z')
lowercharacters ;
else if (str[i] > 'A' && str[i] < 'Z')
uppercharacters ;
else if (str[i] == ' ')
spaces ;
else if (str[i] > '0' && str[i] < '9')
numbers ;
else if (str[i] == ' ' && str[i 1] != ' ');
words ;
}
printf("Spaces = %d\n", spaces);
printf("numbers = %d\n", numbers);
printf("Upper Case characters = %d\n", uppercharacters);
printf("Lower Case characters = %d\n", lowercharacters);
printf("Words = %d\n", words 1);
return 0;
}
CodePudding user response:
As for the words i found a new way to count them. By counting spaces 1 but i want to count them correctly
Code fails due to ;
at the end of the else if()
.
Tip Good compilers with all warnings enabled will warn about that.
Save time, enable all warnings.
// v !!!
else if(str[i]==' ' && str[i 1]!=' ');
words ;
Even if corrected to
else if(str[i]==' ' && str[i 1]!=' ')
words ;
Still fails with input like " abc"
(lead space) reports as 2 words
Instead count the occurrences of a letter following a non-letter.
char previous = '\n';
for(i=0; str[i] != '\0'; i ) {
if (isalpha(str[i]) && !isalpha(previous)) {
words ;
}
previous = str[i];
}
Make you own helper functions if standard ones like is...()
are not allowed.
CodePudding user response:
You should use if(str[i]>='a' && str[i]<='z')
instead of if(str[i]>'a' && str[i]<'z')
. You don't want to exclude the characters z and a from being tested.
CodePudding user response:
For the counting words part, notice that there is one misplaced semicolon after your last else if
statement. The number of words won't be 100% correct if you fix that typo, but you might be able to work from there :)