How to extract numbers from a string in the C language?

One possible way to extract numbers from a string is by using library functions and loops in the C programming language.

  1. Iterate through each character of the string and check if it is a numeric character.
  2. If the current character is a numerical character, then add it to a new string.
  3. If the current character is not a numeric character, check if the new string is empty. If it is not empty, convert the new string to a number, save it, and then clear the new string.
  4. The handling of the last character is similar to step 3, but special attention is required because the last character may be a numerical character.

Here is an example code:

#include <stdio.h>
#include <ctype.h>

int main() {
    char str[] = "abc123def456";
    char numStr[100];  // 用于存储提取到的数字字符串
    int num;  // 存储提取到的数字

    int i, j = 0;
    for (i = 0; str[i] != '\0'; i++) {
        if (isdigit(str[i])) {
            numStr[j++] = str[i];
        } else {
            if (j > 0) {
                numStr[j] = '\0';  // 添加字符串结束符
                num = atoi(numStr);  // 将字符串转换为整数
                printf("%d\n", num);  // 输出提取到的数字
                j = 0;  // 清空数字字符串
            }
        }
    }

    // 处理最后一个数字
    if (j > 0) {
        numStr[j] = '\0';
        num = atoi(numStr);
        printf("%d\n", num);
    }

    return 0;
}

The above code extracts numbers from a string and outputs them, the output is:

123
456

Note: The above code assumes that the numbers in the string are integers. If the string contains decimals, another function like atof should be used for processing. Additionally, the code assumes that the extracted numbers do not exceed the representation range of integers. If they do, another method should be used for handling them.

bannerAds