首先,我的目标是:把一个句子变成一个C字符串。反复阅读句子,看看某个字母出现了多少个实例。
这段代码有点用,但没有给出正确的数字?不确定原因:

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

int tracker=0;
int letterCount (char *sentence)
{
    int s=strlen(sentence);
    int i=0;


    for (i=0; i<s; i++){
        if (sentence[i]=='h') {
            tracker++;
        }
    }
    return tracker;
}

int main(int argc, const char * argv[])
{

    char *string="Hi there, what's going on? How's it going?";


    letterCount(string);

    printf("this sentensce has %i H's", tracker);


    return 0;
}

我得到的结果是:
this sentensce has 2 H's

不完全正确。有什么想法吗?

最佳答案

如果您指的是不区分大小写的H:

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

int tracker=0;
int letterCount (char *sentence)
{
    int s=strlen(sentence);
    int i=0;


    for (i=0; i<s; i++){
        if (sentence[i]=='h' || sentence[i]=='H') {  //'h' is not the same as 'H'
            tracker++;
        }
    }
    return tracker;
}

int main(int argc, const char * argv[])
{

    char *string="Hi there, what's going on? How's it going?";


    letterCount(string);

    printf("this sentensce has %i H's", tracker);


    return 0;
}

你刚刚把代码中的小写字母和大写字母错放了。
记住,C语言是区分大小写的!

关于c - 遍历C字符串不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11514152/

10-12 22:29