使用c语言 ,怎么获取不定长字符串“-X-xxx”中的不定长数字X
时间: 2024-05-09 12:19:23 浏览: 16
可以使用C语言中的字符串处理函数和正则表达式来获取不定长字符串中的不定长数字。
方法一:使用字符串处理函数
1. 先找到字符串中第一个“-”和第二个“-”的位置,分别为start和end。
2. 利用字符串函数strncpy()将X复制到一个新的字符串中,即strncpy(dest, src+start+1, end-start-1),其中dest为目标字符串,src为原字符串。
3. 使用字符串函数atoi()将新字符串转换为整数。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "-1234567-xxx";
int start, end;
char num_str[100];
int num;
start = strchr(str, '-') - str; // 找到第一个“-”的位置
end = strchr(str+start+1, '-') - str; // 找到第二个“-”的位置
strncpy(num_str, str+start+1, end-start-1); // 复制X到新字符串中
num_str[end-start-1] = '\0'; // 新字符串结尾加上'\0'
num = atoi(num_str); // 将新字符串转换为整数
printf("num = %d\n", num);
return 0;
}
```
方法二:使用正则表达式
可以使用正则表达式库regex.h,使用正则表达式匹配字符串中的数字。
示例代码:
```c
#include <stdio.h>
#include <regex.h>
int main() {
char str[] = "-1234567-xxx";
regex_t reg;
regmatch_t pmatch[2];
char num_str[100];
int num;
regcomp(®, "-\\([0-9]+\\)-", REG_EXTENDED); // 编译正则表达式
regexec(®, str, 2, pmatch, 0); // 执行正则表达式匹配
strncpy(num_str, str+pmatch[1].rm_so, pmatch[1].rm_eo-pmatch[1].rm_so); // 复制匹配到的数字
num_str[pmatch[1].rm_eo-pmatch[1].rm_so] = '\0'; // 新字符串结尾加上'\0'
num = atoi(num_str); // 将新字符串转换为整数
printf("num = %d\n", num);
regfree(®); // 释放正则表达式
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)