正如您在后面的示例中所看到的,我正在比较lyric变量中的单词,我想得到计数的唯一单词,但结果返回0
。虽然结果中有3个相似的单词,但它不会进入if块。什么可能导致这个问题?
您可以快速通过this应用程序进行测试。
来源
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
char lyric[] ="lorem ipsum is printing\nlorem ipsum is letters";
int i = 0, j = 0, k = 0, y = 0, l = 0, s = 0;
s = sizeof(lyric)/sizeof(char);
for(k; k<s; ++k)
{
if(lyric[k] == ' ')
++l;
if(lyric[k] == '\n')
++l;
}
char *row;
char *temp[l];
row = strtok (lyric," \n");
while (row != NULL)
{
temp[i++] = row;
row = strtok (NULL, " \n");
}
for (i=0;i<l; ++i){
for (j=(i+1);j<l; ++j){
printf("%s == %s\n", temp[i], temp[j]);
if(temp[i] == temp[j]){
y++;
}
}
}
printf("Unique word count : %d",y);
return 0;
}
结果
lorem == ipsum
lorem == is
lorem == printing
lorem == lorem
lorem == ipsum
lorem == is
ipsum == is
ipsum == printing
ipsum == lorem
ipsum == ipsum
ipsum == is
is == printing
is == lorem
is == ipsum
is == is
printing == lorem
printing == ipsum
printing == is
lorem == ipsum
lorem == is
ipsum == is
Unique word count : 0
答案 0 :(得分:4)
答案 1 :(得分:1)
这里的问题是你的比较涉及两个指针,即temp [i]和temp [j]只是指向内存的指针 你需要比较的是你可以通过使用星号(*)运算符解除引用指针来指出的值所指出的值,即 (* temp [i])和(* temp [j])或者如果您不想手动执行此操作 如上所述使用strcmp。 请参阅此 C String -- Using Equality Operator == for comparing two strings for equality