【问题标题】:C++ string array about nums关于nums的C++字符串数组
【发布时间】:2020-05-17 06:40:18
【问题描述】:

假设字符串是 "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;
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。您需要做的第一件事是发布您已经尝试过的代码,或者显示您的进度。这里的大多数人不会为你从头开始编写代码。
  • 清楚你需要什么,因为这看起来像XY problem。要提取数字,您可以在逐个字符检查字符串时使用isdigit()
  • 请更具体地说明您的问题。是什么阻止你这样做?如果您的主要问题是数组的大小,那么现在是了解std::vector 的好时机。
  • 您是否尝试从字符串中解析和提取数字并将其放入不同的数组中?您应该检查正则表达式以及如何使用它们。

标签: c++ arrays string


【解决方案1】:

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

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

无需进一步说明。

请看:

#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;
}

【讨论】:

  • 其实我看不懂你的代码,我是新手,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2013-04-19
  • 1970-01-01
相关资源
最近更新 更多