gpt4 book ai didi

c - 在 C 中使用三元运算符比较版本字符串

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:51 25 4
gpt4 key购买 nike

我需要比较两个可能以或不以 .0 结尾的“版本”字符串,以便(例如)10.3.8.9.210.3.8.9.2.0 被认为是相等的。

#include <stdio.h>    
#include <string.h>

int main()
{

char str1[20];
char str2[20];
int ret;

strcpy(str1, "10.3.8.9.2");
strcpy(str2, "10.3.8.9.2.0");
// strcpy(str2, "10.3.8.9.20.0"); This case are invalid case and need to handle properly inside ternary operator

ret=(strlen(str1)> strlen(str2))? strncmp( str1,str2,strlen(str2)):(strncmp( str1,str2,strlen(str1))&&( strlen(str2)==strlen(str1)+2 ));

//printf("ret=%d", ret);

//ret=(strlen(str1)> strlen(str2))? strncmp( str1,str2,strlen(str2)):(strncmp( str1,str2,strlen(str1)));

printf("ret_value=%d", ret);

return 0;

}

上面的代码将 10.3.8.9.210.3.8.9.20.0 视为相等,这是不正确的。我已尝试按如下所示更新代码,但由于 strncmp() 在成功时返回 0,因此没有给出预期的结果。

似乎我没有在三元运算符中正确处理这种情况。将两个表达式的返回值存储在单独的变量中可能可以解决此问题,但想知道如何使用三元运算符实现此目的。

最佳答案

需要先比较str1str2的最短公共(public)子串,然后再检查每个字符串的余数。这是一个不使用三元运算符进行字符串比较的解决方案:

#include <stdio.h>
#include <string.h>

int compare_versions(const char *a, const char *b)
{

size_t len1, len2, shortest;

// Return a negative value for invalid inputs.
if (!a || !b) { return -1; }

//First, get the length of the shortest string.
len1 = strlen(a);
len2 = strlen(b);
shortest = len1 < len2 ? len1 : len2;

// If the first sections of the strings are different, they do not match.
if (strncmp(a, b, shortest) != 0) { return 0; }

// Otherwise, check each string: if an "extension" exists, it must be ".0".
if (a[shortest] && strcmp(&a[shortest], ".0") != 0) { return 0; }
if (b[shortest] && strcmp(&b[shortest], ".0") != 0) { return 0; }

// If both strings end with ".0" or nothing, they match.
return 1;

}

int main(int argc, char *argv[])
{
printf("Return value: %d\n", compare_versions("10.3.8.9.2", "10.3.8.9.2"));
printf("Return value: %d\n", compare_versions("10.3.8.9.2.0", "10.3.8.9.2.0"));
printf("Return value: %d\n", compare_versions("10.3.8.9.2.0", "10.3.8.9.2"));
printf("Return value: %d\n", compare_versions("10.3.8.9.2", "10.3.8.9.2.0"));
printf("Return value: %d\n", compare_versions("10.3.8.9.20", "10.3.8.9.2"));
return 0;
}

可以在线运行以上代码here .如果您真的需要使用三元运算符,可以重新组织字符串比较逻辑,但我不确定它是否具有可读性。

关于c - 在 C 中使用三元运算符比较版本字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27622512/

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