首页 > 解决方案 > 关于nums的C++字符串数组

问题描述

假设字符串是“Asah1234&^%736hsi)(91”,而不是在三个数组中存储 1234,736,91

一般来说,我想把每个连续的数字放在每个数组中。问题:我需要多少个数组,每组数字的大小是多少,如何制作循环。我想写一个函数来做到这一点。

#include<iostream> 
using namespace std;

void splitString(string str)
{
    string  num;
    for (int i = 0; i < str.length(); i++)
    {
        if (isdigit(str[i]))
            num.push_back(str[i]);
    }
    cout << num << endl;
}
int countnum( string str)
{
    string  num;
    int sum = 0;
    for (int i = 0; i < str.length(); i++)
    {
        if (isdigit(str[i]))
            sum++;
    }
    cout << sum << endl;
    return 0;
}
int main()
{
    const int MAXLEN = 100;
    char str[MAXLEN];
    printf("please enter strings:");
    scanf_s("%s", str, MAXLEN);
    splitString(str);
    countnum( str);

    return 0;
}

标签: c++arraysstring

解决方案


也许我在这里有一个误解。然后请发表评论,我将删除答案。

这是一项标准任务,将使用正则表达式解决。它只是一个变量的定义,并用它的范围构造函数初始化这个变量。所以,单线。

无需进一步声明。

请参见:

#include <iostream>
#include <string>
#include <regex>
#include <vector>

std::regex re{ R"(\d+)" };

int main() {

    // The input string with test data
    std::string test{"Asah123&^%736hsi)(918"};

    // Define a variable numbers and use the range constructor to put all data in it
    std::vector numbers(std::sregex_token_iterator(test.begin(), test.end(), re), {});

    // Show the result on the screen
    for (const auto& n : numbers) std::cout << n << "\n";

    return 0;
}

推荐阅读