c++ - 关于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;
}
解决方案
也许我在这里有一个误解。然后请发表评论,我将删除答案。
这是一项标准任务,将使用正则表达式解决。它只是一个变量的定义,并用它的范围构造函数初始化这个变量。所以,单线。
无需进一步声明。
请参见:
#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;
}
推荐阅读
- sql - postgreSQL如何选择具有多个元素的数组查询
- reveal.js - Reveal.js 无法在 ios9.3 中加载
- python - 如何在 python sql 查询中使用“LIKE”
- bash - 如何遍历bash中的子目录?
- c - 为什么本地时间系统调用在我的可执行文件中以 UTC 给出时间?
- google-chrome - 可以在选定的时间(离线)通知chrome通知吗?
- python - np.linalg.solve 和 scipy.linalg.cho_solve 之间的性能差距
- flask - 来自 Azure 容器的 Flask 的 send_from_directory
- python - 使用 matplotlib 问题显示两个数字
- javascript - 从 API 读取并比较日期以显示某些内容