对于C的语言的字符串比较,目前使用比较多的是将版本分段进行比较,下面就是使用C语言实现的版本比较,可用于物联网、嵌入式等的固件版本检测。
#define VERSION_PRE_LEN 10
/**
* 将字符串形式的版本号转为数组形式的版本号
* @param version 字符串版本号
* @param ver_arr 数组形式版本号
* @return
*/
int get_version(char *version, int *ver_arr)
{
if (version == NULL)
return -1;
int index = 0;
char num_str[VERSION_PRE_LEN];
char *cur = version;
char *pos = strchr(version, '.');
while (pos != '\0') {
memset(num_str, 0, VERSION_PRE_LEN);
if (cur == version) {
memcpy(num_str, cur, pos - cur);
} else {
memcpy(num_str, cur + 1, pos - cur);
}
ver_arr[index] = atoi(num_str);
cur = pos;
pos = strchr(pos + 1, '.');
index++;
}
memset(num_str, 0, VERSION_PRE_LEN);
memcpy(num_str, cur + 1, version + strlen(version) - cur);
ver_arr[index] = atoi(num_str);
return 0;
}
/**
* 字符串形式的版本号比较
* @param version1
* @param version2
* @param count 段数
* @return 0: version1=version2, 1: version1>version2, -1:version1<version2
*/
int compare_version(char *version1, char *version2, int count)
{
int ver_arr1[count];
int ver_arr2[count];
get_version(version1, ver_arr1);
get_version(version2, ver_arr2);
// 一段一段的比较
for (int index = 0; index < count; index++) {
if (ver_arr1[index] > ver_arr2[index]) {
return 1;
} else if (ver_arr1[index] < ver_arr2[index]) {
return -1;
}
}
return 0;
}
测试
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char version1[] = "42345.724345.2323450.23450.248.25234520";
char version2[] = "42345.724345.2323450.23450.248.25234520";
if (compare_version(version1, version2, 6) > 0) {
printf("version1 > version2");
} else if (compare_version(version1, version2, 6) < 0) {
printf("version1 < version2");
} else {
printf("version1 = version2");
}
return 0;
}