我试图比较两个不同长度的char *的字符串文字值。它们没有null终止符,所以我不能使用strcmp。我该如何判断他们是否平等?有没有我可以使用的方法?
示例代码:
int main(){
char* one = "milk";
char* two = "dalek! Exterminate!";
char* three = "milk";
//Compare and check to see if they are equal. one and two would return false but one and three would return true
}
答案 0 :(得分:2)
您可以使用memcmp比较字符串直到其中一个字符串结束的点。
int strcmpNoTerminator ( const char * str1, const char * str2, size_t str1len, size_t str2len ) {
// Get the length of the shorter string
size_t len = str1len < str2len ? str1len : str2len;
// Compare the strings up until one ends
int cmp = memcmp(str1, str2, len);
// If they weren't equal, we've got our result
// If they are equal and the same length, they matched
if(cmp != 0 || str1len == str2len) {
return cmp;
}
// If they were equal but one continues on, the shorter string is
// lexicographically smaller
return str1len < str2len ? -1 : 1;
}
请注意,这是因为您的char *实际上不是null终止。在您的示例代码中,one
,two
和three
为空终止。我假设你的问题本身是正确的,而不是你的例子。如果示例是正确的,那么您的char * s将被终止,并且您的问题出在其他地方,在这种情况下,我们需要查看更多代码来帮助。