在一串隐藏着一个或多个数值的字符中,选出字符串中的所有数字字符,并将选出的数字字符重新组成新字符串。如果在第一个数字字符之前有负号,则保留该负号,有多个负号时只保留一个。 例如:输入的字符串为“a-1-2-4sd5 s6”,抽取数字后得到的新字符串为“-12456”。 输入 a-1-2-4sd5 s6 输出 -12456 #include <iostream> using namespace std; void extractNum(char * str); int main() { char s[1024]; cin.getline(s,1024); // 输入一行字符 extractNum(s); // 调用extractNum函数,选出数字 cout<<s<<endl; // 输出选出的数字 return 0; } // 函数extractNum:选出str指向的字符串中的数字,并写回str // 参数:str-指向字符串 void extractNum(char * str) { // 请在此添加代码,实现函数extractNum ....... }
时间: 2023-11-28 15:50:01 浏览: 53
以下是实现函数 `extractNum` 的代码:
```python
void extractNum(char * str){
int n = strlen(str);
string res = "";
bool hasNegative = false;
for(int i = 0; i < n; i++){
if(str[i] == '-'){
if(!hasNegative){
res += '-';
hasNegative = true;
}
}
else if(str[i] >= '0' && str[i] <= '9'){
res += str[i];
}
}
strcpy(str, res.c_str());
}
```
具体思路如下:
1. 遍历字符串 `str` 中的每个字符;
2. 如果当前字符为负号 `-`,且之前没有出现过负号,则将其添加到结果字符串 `res` 中,并标记已出现过负号;
3. 如果当前字符为数字,则将其添加到结果字符串 `res` 中;
4. 最后将结果字符串 `res` 转换为 C 风格字符串,并将其复制回原字符串 `str` 中。
相关问题
输入一个字符串,每个字符串由字母和数字组成,将数字选出,求和。
可以使用 Python 中的 re 模块来实现该功能。首先,使用 re.findall() 函数来找到所有的数字,然后使用 map() 函数将找到的数字转换为整数,最后使用 sum() 函数求和。
示例代码:
```
import re
s = "hello123world456"
numbers = re.findall(r'\d+', s)
numbers = list(map(int, numbers))
result = sum(numbers)
print(result)
```
输出:579
本关任务:在一串隐藏着一个或多个数值的字符中,选出字符串中的所有数字字符,并将选出的数字字符重新组成新字符串。如果在第一个数字字符之前有负号,则保留该负号,有多个负号时只保留一个。 例如:输入的字符串为“a-1-2-4sd5 s6”,抽取数字后得到的新字符串为“-12456”。用C++语言
可以使用C++中的字符串和循环结构来实现此任务,示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "a-1-2-4sd5 s6";
string res = "";
bool has_negative = false; // 标记是否已有负号
for (int i = 0; i < s.size(); i++) {
if (s[i] >= '0' && s[i] <= '9') { // 如果当前字符是数字字符,则加入结果字符串
res += s[i];
} else if (s[i] == '-') { // 如果当前字符是负号
if (!has_negative && i == 0) { // 如果是第一个字符,则加入结果字符串
res += s[i];
has_negative = true;
} else if (s[i - 1] == '-') { // 如果前一个字符也是负号,则不加入结果字符串
continue;
} else { // 否则加入结果字符串
res += s[i];
has_negative = true;
}
}
}
cout << res << endl;
return 0;
}
```
输出结果为:-12456