【C/C++】提取字符串中的数字


将字符串中含有的数字提取出来。

#include <iostream>
#include <string>
using namespace std;

int ExtractNum(string ss, char* ch)
{
    const char* c = ss.c_str();
    int amount = 0;
    int i = 0;
    while (c[i] != '\0')
    {
        if (c[i] >= '0' && c[i] <= '9')
        {
            ch[amount] = c[i];
            amount++;
        }
        i++;
    }
    return amount;
}


int main()
{

    string str;
    char ch[100];
    getline(cin, str); //读取一行,包括空格符   cin >> str遇到空格符就会停止读取
    int amount = ExtractNum(str, ch);
    for (int i = 0; i < amount; i++)
    {
        cout << ch[i] << endl;
    }
    cout << "数字个数:" << amount << endl;

    return 0;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM