使用c++ string类,删除给出的string中的所有r字符
时间: 2024-03-08 16:48:24 浏览: 12
可以使用 string 类的 erase() 函数结合迭代器来删除给定字符串中的所有 r 字符。具体实现步骤如下:
1. 遍历字符串中的每个字符,如果该字符是 r,则删除该字符。
2. 重复上述步骤,直到字符串中不存在 r 字符为止。
代码实现如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
size_t pos = str.find('r');
while (pos != string::npos) {
str.erase(pos, 1);
pos = str.find('r', pos);
}
cout << str << endl;
return 0;
}
```
上述代码中,我们使用了 string 类的 find() 函数来查找字符串中是否存在字符 r,如果存在则返回字符所在的位置,否则返回 string::npos。然后使用 erase() 函数删除该字符,继续查找下一个字符 r 的位置,直到字符串中不存在字符 r 为止。
执行上述代码后,输出结果为:
```
hello wold
```
可以看到,字符串中的所有 r 字符都被删除了。
相关问题
c++string类遍历字符串,给出案例
以下是使用C++中的string类遍历字符串的示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World!";
int len = str.length();
// 使用 for 循环遍历字符串
std::cout << "for 循环遍历字符串:" << std::endl;
for (int i = 0; i < len; i++) {
std::cout << str[i] << std::endl;
}
// 使用迭代器遍历字符串
std::cout << "迭代器遍历字符串:" << std::endl;
std::string::iterator it;
for (it = str.begin(); it != str.end(); it++) {
std::cout << *it << std::endl;
}
return 0;
}
```
输出结果为:
```
for 循环遍历字符串:
H
e
l
l
o
W
o
r
l
d
!
迭代器遍历字符串:
H
e
l
l
o
W
o
r
l
d
!
```
C++字符串的使用-string类
C++中的string类是一个非常方便的字符串处理工具,它可以像普通的字符串一样进行赋值、比较、拼接等操作,同时还支持很多高级的字符串处理方法。
使用string类需要包含头文件<string>,定义一个string变量可以直接使用赋值运算符或构造函数进行初始化,例如:
```c++
#include <string>
using namespace std;
string s1 = "hello"; // 直接赋值
string s2("world"); // 构造函数
```
字符串的拼接可以使用加号运算符或者append方法,例如:
```c++
string s3 = s1 + " " + s2; // 使用加号运算符
s1.append(s2); // 使用append方法
```
string类还支持很多其他的方法,例如查找、替换、截取、转换大小写等等,具体可以查看官方文档或教程。