c - 迭代 C 字符串不起作用

标签 c string iteration

首先,我对这段代码的目标是:将一个句子放入一个 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/

相关文章:

c++ - 如何在 C++ 中使用字符串修饰符创建新字符串?

字符串文字的C优化

c - 从另一个函数调用构造函数时的存储持续时间

c - 可变参数函数中的大小整数和提升

java - 是否有一个特殊的字符集将所有可能的字节值映射到有效字符并映射回来?

python - 遍历包含 8526 个项目的列表,获取索引超出范围错误

python - 如何将不相等的列表压缩为第一个列表与其他列表的乘积?

.net - 控制迭代循环内的递归

c - 如何将SIP消息内容传递到C应用程序中

c++ - 如何通过套接字将数据作为 XML 传递?