所以我有以下测试代码:
#include <string.h>
#include <stdio.h>
int main(int argc, char* argv[]){
int retVal = strcmp("", "");
printf("%d\n", retVal);
return 0;
}
对我来说,它似乎总是打印出 0,即 ""和 ""总是彼此相等。但我很好奇。这是 strcmp 保证的东西,还是它有可能因实现而异?也许我只是偏执,但我研究过足够多的奇怪系统,所以知道不同实现的危险。
更新: 我决定澄清一下,以证明我的偏执是合理的。我在程序中真正做的更类似于此:
#include <string.h>
#include <stdio.h>
int doOperation(const char* toCompare){
//do stuff in here
int compResult = strcmp(toCompare, "");
//do more stuff depending on compResult
}
int main(int argc, char* argv[]){
const char* myString = "";
doOperation(myString);
return 0;
}
我想确保 doOperation 中的事情能够正确进行。请注意,这只是一个示例。在我的 doOperation 函数中,我不会真正知道 toCompare
的值。
最佳答案
如果两个字符串的 NULL 终止符之前的所有字符完全相同,则该字符串等于另一个字符串。由于 ""
没有字符,因此与 ""
相比,它符合该定义。
关于在 C 中比较 ""和 "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7862473/