Using the function strcmp
if (strcmp(&text[i], "?") == 0 || strcmp(&text[i], "!") == 0 || strcmp(&text[i], ".") == 0)
does not make a sense. The expression in the if statement will be evaluated to true only for the last character in the string text
provided that the last character is equal to one of the characters '?'
, '!'
and '.'
.
Instead you should use standard C functions strspn
and strcspn
. For example
size_t count_sentences( string text )
{
const char *delim = "?!.";
size_t count = 0;
for ( text += strcspn( text, delim ); *text != '\0'; text += strcspn( text, delim ) )
{
++count;
text += strspn( text, delim );
}
return count;
}
The function will return 1 for example for the string "Executing..."
. Indeed there is only one statement though there are three characters '.'
.
Here is a demonstration program.
#include <stdio.h>
#include <string.h>
typedef char *string;
size_t count_sentences( string text )
{
const char *delim = "?!.";
size_t count = 0;
for ( text += strcspn( text, delim ); *text != '\0'; text += strcspn( text, delim ) )
{
++count;
text += strspn( text, delim );
}
return count;
}
int main(void)
{
string text = "Strange... Why are you using strcmp?! Use strspn and strcspn!!!";
printf( "The text\n\"%s\"\ncontains %zu sentences.\n",
text, count_sentences( text ) );
return 0;
}
The program output is
The text
"Strange... Why are you using strcmp?! Use strspn and strcspn!!!"
contains 3 sentences.