在C比较版本号 [英] comparing version numbers in c
问题描述
我看到很多答案在其他语言的这个问题,但我试图找到一种方法来比较给定为字符串2版本号。例如:
STR1 =141.1.23
STR2赛车=141.1.22
我试图找到一种方法来比较字符串中的整数值,看看哪一个是较大的。 (在这种情况下STR1将更大)。我想过用某个与和的atoi组合strtok函数,但我知道我不会是能够一次来标记2串。有什么建议?
我知道我不会是能够一次来标记2串。
块引用>幸运的是,你并不需要:一个函数,它接受一个字符串,并使用
strtok_r
(使用重入版本解析这三个整数,这是一个很大更安全)。strunct version_t {
INT专业;
INT未成年人;
INT构建;
};version_t parse_ver(为const char * version_str){
version_t资源;
//使用strtok_r分割字符串,并要与atoi令牌转换为整数
返回水库;
}现在你可以叫
parse_ver
两次,得到两个version_t
值,比较它们并排侧。P.S。如果采用约定总是用前导零填充到一个特定的长度,即数字确保你写
141.1.03
,而不是141.1.3
,您可以用替代字典一个整型比较。I am seeing a lot of answers for this problem in other languages but I am trying to find out a way to compare 2 version numbers given as strings. For example
str1 = "141.1.23" str2 = "141.1.22"
I am trying to find a way to compare the integer values in the strings to see which one is larger. (In this case str1 would be larger). I thought about using sometime of combination with atoi and strtok but I know I wont be able to tokenize 2 strings at once. Any advice?
解决方案I know I wont be able to tokenize 2 strings at once.
Fortunately, you do not need to: make a function that takes a string, and parses it for three integer numbers using
strtok_r
(use a reentrant version, it's a lot safer).strunct version_t { int major; int minor; int build; }; version_t parse_ver(const char* version_str) { version_t res; // Use strtok_r to split the string, and atoi to convert tokens to ints return res; }
Now you can call
parse_ver
twice, get twoversion_t
values, and compare them side-by-side.P.S. If you adopt a convention to always pad the numbers with leading zeros to a specific length, i.e. make sure that you write
"141.1.03"
and not"141.1.3"
, you could substitute integer comparison with lexicographic one.这篇关于在C比较版本号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!