问题描述】 假定输入的字符串中只包含字母和*号。请编写程序,字符串中除了字符串前导和尾部的*号之外,将字符串中其他的*号全部删除.最后输出处理后的字符串。 【输入形式】 ***a*B**c**** 【输出形式】 ***aBc**** 用c++编写程序
时间: 2024-11-21 21:28:10 浏览: 37
在C++中,你可以使用`std::string`的`find`和`replace`方法来实现这个需求。这里是一个简单的例子:
```cpp
#include <iostream>
#include <string>
std::string remove_internal_asterisks(const std::string& input) {
// 寻找第一个非星号字符的索引
size_t start_index = input.find_first_not_of("*");
// 如果找不到非星号字符,则说明整个字符串都是星号,直接返回 ""
if (start_index == std::string::npos) {
return "";
}
// 寻找最后一个非星号字符的索引
size_t end_index = input.find_last_not_of("*", start_index);
// 用实际的字符替换掉中间的星号
std::string output(input.begin() + start_index, input.begin() + end_index + 1); // 加一是因为包括end_index对应的字符
return output;
}
int main() {
std::string input = "***a*B**c****";
std::string result = remove_internal_asterisks(input);
std::cout << "Output: " << result << std::endl; // 输出 ***aBc****
return 0;
}
```
这段代码首先查找字符串的第一个和最后一个非星号字符的索引,然后创建一个新的字符串,只包含这两个索引之间的字符。注意,`find_last_not_of`的第二个参数是从`start_index`开始搜索的。
如果输入的字符串全由星号组成,函数将返回空字符串。
阅读全文
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)