I am trying to calculate the number of sentences inside any text on the basis that the end of each sentence may be !
, ?
or .
, but when I used strcmp()
it doesn't work as expected. so if the text contains !
and compared with character constant !
it doesn't give the correct output as 0 as assumed.
Although, I tried to test the outputs to understand what took place led to such result but I couldn't understand so can anyone help ?
Thank you.
here is my code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int count_sentences(string text);
int main(void)
{
string text = get_string("text: ");
//printf("%s\n", text);
count_sentences(text);
//printf("%i\n", strcmp("!", "!"));
}
int count_sentences(string text)
{
int string_length = strlen(text);
int num_of_sentences = 0;
const char sent_ind1 = '?';
const char sent_ind2 = '!';
const char sent_ind3 = '.';
//printf("%c %c %c", sent_ind1, sent_ind2,
//sent_ind3);
for (int i = 0; i < string_length; i++)
{
int value1 = strcmp(&text[i], &sent_ind1);
int value2 = strcmp(&text[i], &sent_ind2);
int value3 = strcmp(&text[i], &sent_ind3);
if (value1 == 0 || value2 == 0 || value3 == 0)
{
num_of_sentences += 1;
}
//printf("1- %i 2- %i 3- %i i- %c c- %c si0 %c si1 %c si2 %c\n",
//value1, value2, value3, i, text[i], sent_ind1, sent_ind2,
//sent_ind3);
//printf("1- %i 2- %i 3- %i i- %i\n",
//sent_ind1, sent_ind2, sent_ind3, text[i]);
}
//printf("string length equal %i and number of sentences equal %i.\n",
//string_length, num_of_sentences);
return num_of_sentences;
}