C语言如何提取CPU0_C2D1中的三个数字
时间: 2024-04-12 09:30:27 浏览: 14
在C语言中,你可以使用正则表达式库(例如PCRE库)或自定义函数来提取字符串中的数字。下面是一个示例代码,使用自定义函数来提取"CPU0_C2D1"中的三个数字:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void extractNumbers(const char* string, int* numbers, int count) {
int i = 0;
int j = 0;
int len = strlen(string);
char temp[20]; // 用于存储提取出的数字字符串
int tempIndex = 0;
while (i < len && j < count) {
if (isdigit(string[i])) {
// 提取数字字符串
while (i < len && isdigit(string[i])) {
temp[tempIndex++] = string[i++];
}
temp[tempIndex] = '\0';
// 将数字字符串转换为整数并存储
numbers[j++] = atoi(temp);
// 重置临时变量
tempIndex = 0;
}
else {
i++;
}
}
}
int main() {
char string[] = "CPU0_C2D1";
int numbers[3];
extractNumbers(string, numbers, 3);
for (int i = 0; i < 3; i++) {
printf("Number %d: %d\n", i+1, numbers[i]);
}
return 0;
}
```
在这个示例中,我们定义了一个自定义函数`extractNumbers`,它接受一个字符串和一个整数数组作为参数,并从字符串中提取数字并存储在数组中。我们使用两个指针`i`和`j`来遍历字符串和数组。当遇到数字字符时,我们提取连续的数字字符并存储在临时数组`temp`中。然后,我们使用`atoi`函数将临时数组中的数字字符串转换为整数,并将其存储在数组中。最后,我们通过循环打印出提取出的三个数字。请注意,这个示例假设输入字符串中的每个数字都是整数类型。如果有其他要求,请相应地调整代码。