gpt4 book ai didi

比较 2 个不同长度的 char*(不带空终止符)

转载 作者:行者123 更新时间:2023-11-30 20:14:45 25 4
gpt4 key购买 nike

我正在尝试比较两个不同长度的 char* 的字符串文字值。它们没有空终止符,所以我不能使用 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

}

最佳答案

您可以使用 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 结尾的。在您的示例代码中,onetwotwo 均以 null 结尾。我假设你的问题本身是正确的,而不是你的例子。如果示例正确,那么您的 char * 将以 null 结尾,并且您的问题出在其他地方,在这种情况下,我们需要查看更多代码来提供帮助。

关于比较 2 个不同长度的 char*(不带空终止符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24770665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com