输入一个字符串,内有数字和非数字字符,如:a123x456&17960?302tab5876, 将其中连续的数字作为一个整数,依次存放到一整型数组中。如123放在a[0]中,456放在a[1]中…统计共有多少个整数,并输出这些数。
时间: 2024-02-06 09:11:12 浏览: 26
好的,可以使用正则表达式来匹配连续的数字,然后将其转换为整数并存放到数组中。下面是示例代码:
```python
import re
s = 'a123x456&17960?302tab5876'
pattern = re.compile(r'\d+')
nums = [int(x) for x in re.findall(pattern, s)]
count = len(nums)
print(f"共有{count}个整数:{nums}")
```
输出结果为:
```
共有5个整数:[123, 456, 17960, 302, 5876]
```
相关问题
用c++编写:输入一个字符串,内有数字和非数字字符,如:a123x456&17960?302tab5876, 将其中连续的数字作为一个整数,依次存放到一整型数组中
好的,下面是用C++编写的实现:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string str;
vector<int> nums;
cout << "请输入一个字符串:";
getline(cin, str);
int i = 0, n = str.length();
while (i < n) {
if (isdigit(str[i])) {
int num = 0;
while (i < n && isdigit(str[i])) {
num = num * 10 + (str[i] - '0');
i++;
}
nums.push_back(num);
} else {
i++;
}
}
int m = nums.size();
int arr[m];
for (int j = 0; j < m; j++) {
arr[j] = nums[j];
}
cout << "提取的整型数组为:";
for (int j = 0; j < m; j++) {
cout << arr[j] << " ";
}
cout << endl;
return 0;
}
```
程序思路如下:
1. 首先读入一个字符串,使用 `getline()` 函数可以读入含空格的字符串;
2. 定义一个 `vector<int>` 类型的数组 `nums`,用于存放提取出来的整数;
3. 使用循环遍历字符串中的每一个字符,如果是数字,就将它与后面的数字连起来形成一个整数,存放到 `nums` 中;
4. 最后将 `nums` 中的整数放入一个整型数组 `arr` 中;
5. 输出整型数组 `arr`。
这里使用了 STL 库中的 `vector` 类型,可以方便地动态扩展数组大小,使得代码更简洁易懂。
用c++\输入一个字符串,内有数字和非数字字符,如:a123x456&17960?302tab5876, 将其中连续的数字作为一个整数,依次存放到一整型数组中。如123放在a[0]中,456放在a[1]中…统计共有多少个整数,并输出这些数。
好的,可以使用正则表达式来匹配连续的数字,然后将其转换为整数并存放到数组中。下面是示例代码:
```c++
#include <iostream>
#include <regex>
#include <vector>
using namespace std;
int main() {
string s = "a123x456&17960?302tab5876";
regex pattern("\\d+");
smatch match;
vector<int> nums;
while (regex_search(s, match, pattern)) {
nums.push_back(stoi(match[0]));
s = match.suffix().str();
}
int count = nums.size();
cout << "共有" << count << "个整数:";
for (int i = 0; i < count; i++) {
cout << nums[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
共有5个整数:123 456 17960 302 5876
```