输入一个字符串,内有数字和非数字字符。例如:a123x456 17960 302tab5876。将其中连续的数字作为一个整数,依次存放到一维数组a中,例如123放在a[0],456放在a[1]……统计共有多少个整数,并输出这些数。

2023-07-30,,

题目内容:输入一个字符串,内有数字和非数字字符。例如:a123x456 17960 302tab5876。将其中连续的数字作为一个整数,依次存放到一维数组a中,例如123放在a[0],456放在a[1]……统计共有多少个整数,并输出这些数。

输入格式:输入一个字符串(允许空格)。

输出格式:第1行输出个数,第2行输出多个整数,用空格分隔。

输入样例:a123X456  7689?89njmk32lnk123

输出样例:

6

123 456 7689 89 32 123

解决思路:
最近同时在学C++和python,正好python又学到正则表达式,

所以我想试试怎么用C++的正则,这样可以大大减少代码数目!

写完之后在VScode里的结果都能对上,但是贴到OJ之后程序运行错误。

而且后面搜了一圈,没有像我一样用正则做这道题的,所以分享一下代码~

 1 #include <iostream>
2 #include <string>
3 #include <regex>
4 using namespace std;
5 int main()
6 {
7 regex pattern("\\d+");
8 string content;
9 getline(cin, content);
10 smatch result;
11 int count = 0;
12 auto begin = content.cbegin();
13 auto end = content.cend();
14 while (regex_search(begin, end, result, pattern))
15 {
16
17 count += 1;
18
19 begin = result[0].second;
20 }
21 cout << count << endl;
22 begin = content.cbegin();
23
24 while (regex_search(begin, end, result, pattern))
25 {
26
27 cout << result[0];
28 begin = result[0].second;
29 if (begin != end)
30 cout << " ";
31 }
32 return 0;
33 }

这个是没有末尾空格的

下面这个是有末尾空格的

 1 #include <iostream>
2 #include <string>
3 #include <regex>
4 using namespace std;
5 int main()
6 {
7 regex pattern("\\d+");
8 string content;
9 getline(cin, content);
10 smatch result;
11
12 int count = 0;
13 int n = result.size();
14 string m[n];
15
16 auto begin = content.cbegin();
17 auto end = content.cend();
18 while (regex_search(begin, end, result, pattern))
19 {
20
21 count += 1;
22 begin = result[0].second;
23 }
24
25 cout << count << endl;
26 begin = content.cbegin();
27 while (regex_search(begin, end, result, pattern))
28 {
29
30 cout << result[0] << " ";
31 begin = result[0].second;
32 }
33
34 return 0;
35 }

输入一个字符串,内有数字和非数字字符。例如:a123x456 17960 302tab5876。将其中连续的数字作为一个整数,依次存放到一维数组a中,例如123放在a[0],456放在a[1]……统计共有多少个整数,并输出这些数。的相关教程结束。

《输入一个字符串,内有数字和非数字字符。例如:a123x456 17960 302tab5876。将其中连续的数字作为一个整数,依次存放到一维数组a中,例如123放在a[0],456放在a[1]……统计共有多少个整数,并输出这些数。.doc》

下载本文的Word格式文档,以方便收藏与打印。