C - 计算字符串中的单词

时间:2017-03-23 22:07:20

标签: c string

我一直在尝试用一个函数来计算C中字符串中的单词数。但是,在某些casas中(如示例中的那个)它应该返回0而不是1 ...任何想法什么可能是错的?

#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; 
}

4 个答案:

答案 0 :(得分:1)

您不应该将'\n'与其他任何空格字符区别对待。

这是一个更简单的版本:

#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; 
}

答案 1 :(得分:1)

我想这个词是除了空格字符之外的任何字符序列。

您的函数返回1,因为遇到新行字符时提供的字符串变量r由于这种情况而增加

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

所以函数实现错误。

可以通过以下方式定义,如演示程序中所示

#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;
}

您预期的输出是

Words: 0

答案 2 :(得分:1)

使用现有角色测试功能的简单说明:

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;
}

答案 3 :(得分:0)

该行:

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

'\n'上查看时,情况完全匹配。

您应该使用if ... else if ...