使用 strcmp 将 c 字符串与 char 进行比较
Comparing c strings to char using strcmp
我正在尝试使用 C 字符串计算 spaces。我不能使用标准字符串。在比较这两个字符的行中,我得到错误“从 'char' 到 'const char*' 的无效转换”。
我知道我需要比较两个 const chars* 但我不确定哪个是哪个。我相信 sentence[] 是 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;
}
我可以这样建议:
for(int i = 0; i < 256; i++) {
if (isspace(sentence[i])) // or sentence[i] == ' '
{
tally++
}
}
您现在要做的是比较一个 char (sentence[i]
) 和一个 c-string (space
),这是行不通的。
请注意,对于
这样的句子,您的实现不会像您期望的那样
"a big space be in here."
因此您需要考虑如何处理多个空间。
strcmp 用于比较两个字符串而不是单个字符与一个字符串。
没有函数:strcmp(char c, char*); // 如果有的话就不合逻辑了!
如果要在字符串中搜索单个字符,只需使用迭代将该字符与所有元素进行比较即可:
iint wordCount(char* sentence)
{
int tally = 0;
char space[2] = " ";
for(int i = 0; i < strlen(sentence); i++)
{
if (sentence[i] == space[0])
{
tally++;
}
}
return tally;
}
如果你真的想计算 space 个字符,我认为下面的方法会更好,因为它会检查 char 数组的结束位置。字符串终止符 (\0) 表示 char 数组的结尾。我不知道你为什么硬编码 256。
int countSpaceCharacters(char* sentence)
{
int count = 0;
int i = 0;
while (sentence[i] != '[=10=]')
{
if (sentence[i] == ' ')
{
count++;
}
i++;
}
return count;
}
但是,如果你想像我从原始方法名称中看到的那样统计单词,你需要想一个更好的方法。因为这个算法在不完美的情况下会失败,例如连续 space 个字符或标点符号周围没有 space 个字符等
我正在尝试使用 C 字符串计算 spaces。我不能使用标准字符串。在比较这两个字符的行中,我得到错误“从 'char' 到 'const char*' 的无效转换”。
我知道我需要比较两个 const chars* 但我不确定哪个是哪个。我相信 sentence[] 是 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;
}
我可以这样建议:
for(int i = 0; i < 256; i++) {
if (isspace(sentence[i])) // or sentence[i] == ' '
{
tally++
}
}
您现在要做的是比较一个 char (sentence[i]
) 和一个 c-string (space
),这是行不通的。
请注意,对于
这样的句子,您的实现不会像您期望的那样"a big space be in here."
因此您需要考虑如何处理多个空间。
strcmp 用于比较两个字符串而不是单个字符与一个字符串。
没有函数:strcmp(char c, char*); // 如果有的话就不合逻辑了!
如果要在字符串中搜索单个字符,只需使用迭代将该字符与所有元素进行比较即可:
iint wordCount(char* sentence)
{
int tally = 0;
char space[2] = " ";
for(int i = 0; i < strlen(sentence); i++)
{
if (sentence[i] == space[0])
{
tally++;
}
}
return tally;
}
如果你真的想计算 space 个字符,我认为下面的方法会更好,因为它会检查 char 数组的结束位置。字符串终止符 (\0) 表示 char 数组的结尾。我不知道你为什么硬编码 256。
int countSpaceCharacters(char* sentence)
{
int count = 0;
int i = 0;
while (sentence[i] != '[=10=]')
{
if (sentence[i] == ' ')
{
count++;
}
i++;
}
return count;
}
但是,如果你想像我从原始方法名称中看到的那样统计单词,你需要想一个更好的方法。因为这个算法在不完美的情况下会失败,例如连续 space 个字符或标点符号周围没有 space 个字符等