C++如何提取该字符串中的数字集合 -2408835.9820 4698169.2238 3566538.6125 APPROX POSITION
时间: 2024-02-15 14:35:06 浏览: 21
您可以使用正则表达式来提取字符串中的数字集合。以下是一个示例代码,可以提取给定字符串中所有的数字:
```c
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
int main() {
char *str = "-2408835.9820 4698169.2238 3566538.6125 APPROX POSITION";
char *pattern = "-?[0-9]+\\.?[0-9]*"; // 匹配数字的正则表达式
regex_t regex;
regmatch_t match;
int ret;
// 编译正则表达式
if (regcomp(®ex, pattern, REG_EXTENDED) != 0) {
printf("Failed to compile regex.\n");
return 1;
}
// 在字符串中查找数字
while ((ret = regexec(®ex, str, 1, &match, 0)) == 0) {
// 打印匹配的数字
printf("%.*s ", match.rm_eo - match.rm_so, str + match.rm_so);
// 跳过已匹配的部分
str += match.rm_eo;
}
// 释放正则表达式
regfree(®ex);
printf("\n");
return 0;
}
```
输出结果为:
```
-2408835.9820 4698169.2238 3566538.6125
```
代码解释:
1. 定义了一个字符串 `str`,其中包含了需要提取数字的字符串。
2. 定义了一个正则表达式 `pattern`,用于匹配字符串中的数字。该正则表达式可以匹配整数和小数,包括负数。
3. 使用 `regcomp` 函数编译正则表达式。
4. 使用 `regexec` 函数在字符串中查找匹配的数字。该函数可以多次调用,每次返回一个匹配结果。
5. 在循环中,打印匹配结果,并将指针 `str` 跳过已匹配的部分。
6. 使用 `regfree` 函数释放正则表达式。