Why is my strchr not looping? I want it to output the number for however many times it sees '.' or ' !' or '?'

88 views Asked by At

I know strchr only gets the first instance. But why is my loop not working. No matter how many times '.' or ' !' or '?' is used in the text. It keeps outputting 3.

 //this finds number of sentences
    int Y = 0;
    while (ch != '\0');
    if(strchr(text,'.') != NULL)
        Y++;
    if(strchr(text,'!') != NULL)
        Y++;
    if(strchr(text,'?') != NULL)
        Y++;
2

There are 2 answers

0
Vlad from Moscow On

For starters it seems there is a typo

while (ch != '\0');
                 ^^^ 

In any case this code snippet

int Y = 0;
while (ch != '\0');
if(strchr(text,'.') != NULL)
    Y++;
if(strchr(text,'!') != NULL)
    Y++;
if(strchr(text,'?') != NULL)
    Y++;

does not make sense because the search of target characters always start from the beginning of text.

The function strchr is not an appropriate function for this task if to use separate calls of the function for each target symbol.

In this case using this function you need three separate loops one for each target symbols.

Here is a demonstrative program that shows how the task can be performed using another string function strcspn.

#include <stdio.h>
#include <string.h>

size_t count_symbols( const char *s, const char *delim )
{
    size_t n = 0;

    while ( *s )
    {
        if ( *( s += strcspn( s, delim ) ) )
        {
            ++n;
            ++s;
        }           
    }

    return n;
}

int main(void) 
{
    const char *s = "Firt. Second? Third! That is all.";

    printf( "%zu\n", count_symbols( s, ".!?" ) );

    return 0;
}

The program output is

4
2
0___________ On
size_t count(const char *haystack, const char *needle)
{
    size_t cnt = 0;

    while(*haystack)
    {
        if(strchr(needle, *haystack++)) cnt++;
    }
    return cnt;
}

int main(void)
{
    printf("%zu\n", count("Hwedgdf,.???,,,,.h.rtfdsg....dfsdgfs?gdfg//..? //.", ".?"));
}

https://godbolt.org/z/fLUsWz