【发布时间】:2013-11-11 17:38:53
【问题描述】:
// Compares the two arguments. If they are equal, 0 is returned. If they
// are not equal, the difference of the first unequal pair of characters
// is returned.
int strcmp(const char* charPointerToArray1, const char* charPointerToArray2) {
int i = 0;
// we need to check if both arrays have reached their terminating character
// because consider the case where array1 = { '\0' } and array2 = { '1', '\0' }
while (charPointerToArray1[i] != '\0' || charPointerToArray2[i] != '\0') {
// while iterating through both char arrays,
// if 1 char difference is found, the 2 char arrays are not equal
if (charPointerToArray1[i] != charPointerToArray2[i]) {
int differenceOfFirstUnequalChars = charPointerToArray1[i] - charPointerToArray2[i];
return differenceOfFirstUnequalChars;
} else {
i++;
}
}
return 0; // charPointerToArray1 == charPointerToArray2
}
于是我在cpp中写了一个字符串比较的方法,搞不明白是什么问题。
【问题讨论】:
-
||应该是&&。然后你需要稍微重写一下逻辑。在您在该行上方评论中的非常示例中,您将超出if条件的范围。 -
我正要说明错误,但我敢打赌 Simple 拥有它的权利。
-
另外,如果两个字符串的长度不同?
-
在什么输入中它不起作用?任何或特殊情况?是否存在误报、误报或两者兼有?
-
当我在 2 个字符串 '\0' 和 'foobar\0' 上运行该方法时,它返回 0 而不是 f 和 '\0' 之间的差异