0

i've been trying to do a function that counts the number of words in a string in C. However, in some casas (as the one in the example) it should return 0 and not 1... any ideas of what could be wrong?

#import <stdio.h>  

int contaPal(char s[]) {          
    int r;     
    int i;     
    r = 0;      

    for (i = 0; s[i] != '\0'; i++) {          
        if (s[i] == '\n')           
            r = r + 0;               

        if (s[i] != ' ' && s[i + 1] == ' ' && s[i + 1] != '\0')             
            r++;        

        if (s[i] != ' ' && s[i + 1] == '\0') {              
            r++;        
        }       
    }          
    return r; 
}  

int main () {   
    char s[15] = { ' ', '\n', '\0' };

    printf("Words: %d \n", (contaPal(s)));
    return 0; 
}
6
  • 1
    @João Pimentel Define the notion of the word. Commented Mar 23, 2017 at 22:09
  • 1
    @João Pimentel If the new line is encountered then r is increased due to this condition if (s[i] != ' ' && s[i + 1] == '\0') { . So the function will return at least 1 for the string you defined. Commented Mar 23, 2017 at 22:10
  • at if (s[i] != ' ' && s[i + 1] == '\0') { : ('\n' != ' ' && '\0' == '\0') become true. Commented Mar 23, 2017 at 22:15
  • Don't check blank characters one by one, you have many of them and this complicates your task(' ', '\t', '\n', '\r'), use isspace from ctype.h. Commented Mar 23, 2017 at 22:17
  • 1
    r = r + 0? heh :) Commented Mar 23, 2017 at 22:19

4 Answers 4

1

You should not treat '\n' differently from any other whitespace character.

Here is a simpler version:

#include <ctype.h>  
#include <stdio.h>  

int contaPal(const char *s) {          
    int count = 0, hassep = 1;

    while (*s) {
        if (isspace((unsigned char)*s) {
            hassep = 1;
        } else {
            count += hassep;
            hassep = 0;
        }
        s++;
    }
    return count;
}

int main(void) {   
    char s[] = " \n";

    printf("Words: %d\n", contaPal(s));
    return 0; 
}
Sign up to request clarification or add additional context in comments.

Comments

1

I suppose that the word is any sequence of characters excluding white space characters.

Your function returns 1 because for the supplied string when the new line character is encountered the variable r is increased due to this condition

    if (s[i] != ' ' && s[i + 1] == '\0') {              
        r++;        
    }  

So the function implementation is wrong.

It can be defined the following way as it is shown in the demonstrative program

#include <stdio.h>
#include <ctype.h>

size_t contaPal( const char s[] ) 
{
    size_t n = 0;

    while ( *s )
    {
        while ( isspace( ( unsigned char )*s ) ) ++s;
        n += *s != '\0';
        while ( *s && !isspace( ( unsigned char )*s ) ) ++s;
    }

    return n;
}  

int main(void) 
{
    char s[] = { ' ', '\n', '\0' };

    printf( "Words: %zu\n", contaPal( s ) );

    return 0;
}

Its output as you expect is

Words: 0

Comments

1

A simple illustration using existing character test functions:

int main(void)
{
    int cnt = 0;
    int numWords = 0;
    BOOL trap = 0; //start count only after seeing a word
    char *sentence = "This is a sentence, too long.";       
    //char *sentence2 = "      ";//tested for empty string also


    while (*sentence != '\0') 
    {
        if ( isalnum (*sentence) ) //word is found, set trap and start count
        {
            sentence++;  //alpha numeric character, keep going
            trap = 1;
        }
        else if ( (( ispunct (*sentence) ) || ( isspace(*sentence) )) && trap)
        {  //count is started only after first non delimiter character is found
            numWords++;
            sentence++;
            while(( ispunct (*sentence) ) || ( isspace(*sentence) ))
            { //handle sequences of word delimiters
                sentence++;
            }
        }
        else //make sure pointer is increased either way
        {
            sentence++;
        }

    }
    return 0;
}

6 Comments

@VladfromMoscow - I did not implement a function, it is a code snippet illustrating how to use additional char test functions ispunct and isspace. To which funcntion are you referring please. I did test this in a small main function by the way.
In any case the code snippet is a part of a function is not it? It is wrong.
What would be the outcome for a sentence containing only whitespaces?
@VladfromMoscow - still not sure to what you are referring, but re-wrote to include main(), surrounding rest of snippet. Does this address your concern?
@A.S.H - ah! thank you. Mis-count by one. I need to test for at least one non delimiter before starting the count.
|
0

The line:

    if (s[i] != ' ' && s[i + 1] == ' ' && s[i + 1] != '\0')             
        r++;

Exactly matches the case when you look on '\n'.

You should use if ... else if ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.