linux C将"REV:3.1"拆分为"REV:3"和"1"两个字符串
时间: 2024-04-14 22:24:30 浏览: 12
在Linux C中,可以使用字符串处理函数来将字符串拆分为多个子字符串。对于将"REV:3.1"拆分为"REV:3"和"1"两个字符串,可以使用strtok函数和strchr函数来实现。
首先,使用strtok函数将原始字符串按照指定的分隔符进行拆分。在这个例子中,分隔符为":"。代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "REV:3.1";
char *token;
token = strtok(str, ":");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ":");
}
return 0;
}
```
运行以上代码,输出结果为:
```
REV
3.1
```
接下来,可以使用strchr函数找到第一个"."字符的位置,并将其替换为"\0",从而将原始字符串分割成两个子字符串。代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "REV:3.1";
char *token;
token = strtok(str, ":");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ":");
}
char *dot = strchr(str, '.');
if (dot != NULL) {
*dot = '\0';
printf("%s\n", dot + 1);
}
return 0;
}
```
运行以上代码,输出结果为:
```
REV
3
1
```