gpt4 book ai didi

使用 strcmp 比较 C 字符串和 char

转载 作者:行者123 更新时间:2023-11-30 21:17:33 25 4
gpt4 key购买 nike

我正在尝试使用 C 字符串来计算空格数。我无法使用标准字符串。在比较两个字符的行中,我收到错误“从‘char’到‘const char* 的无效转换’”。

我知道我需要比较两个 const chars* 但我不确定哪个是哪个。我相信句子[]是char而char space[]是const char*,对吗?我需要使用某种类型的转换来转换第二个,但我不理解我猜的语法。感谢您的帮助<3

int wordCount(char sentence[])
{
int tally = 0;
char space[2] = " ";

for(int i = 0; i > 256; i++)
{
if (strcmp(sentence[i], space) == 0)
{
tally++
}
}

return tally;
}

最佳答案

如果你真的想计算空格字符,我认为下面的方法会更好,因为它检查 char 数组的结束位置。字符串终止符 (\0) 表示 char 数组的结束。我不知道你为什么硬编码 256。

int countSpaceCharacters(char* sentence)
{
int count = 0;
int i = 0;

while (sentence[i] != '\0')
{
if (sentence[i] == ' ')
{
count++;
}
i++;
}

return count;
}

但是,如果您想像我从原始方法名称中看到的那样计算单词数,您需要考虑更好的方法。因为该算法在不完美的情况下会失败,例如具有连续的空格字符或周围没有空格字符的标点符号等。

关于使用 strcmp 比较 C 字符串和 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39520786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com