string类有迭代器吗
时间: 2023-07-21 10:06:49 浏览: 48
是的,C++ STL中的string类拥有迭代器。可以使用迭代器来遍历和修改字符串中的每个字符。例如,使用begin()和end()函数可以获得指向字符串开头和结尾的迭代器,使用++运算符可以移动迭代器到下一个字符位置。以下是一个简单的示例代码:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "hello world";
// 使用迭代器遍历字符串
for (auto it = s.begin(); it != s.end(); ++it) {
cout << *it << " ";
}
cout << endl;
// 使用迭代器修改字符串
for (auto it = s.begin(); it != s.end(); ++it) {
*it = toupper(*it);
}
cout << s << endl;
return 0;
}
```
输出结果为:
```
h e l l o w o r l d
HELLO WORLD
```
相关问题
string类有begin和end迭代器吗
是的,`string` 类有 `begin()` 和 `end()` 方法,可以返回一个迭代器,用于遍历字符串中的字符。
`begin()` 方法返回一个指向字符串第一个字符的迭代器,而 `end()` 方法返回一个指向字符串最后一个字符后面的位置的迭代器(即末尾迭代器)。
例如,下面的代码演示了如何使用 `begin()` 和 `end()` 方法来遍历字符串中的字符:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
for (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
```
运行上面的代码,输出将会是:
```
H e l l o
```
可以看到,我们使用 `begin()` 和 `end()` 方法遍历了字符串中的每个字符,并使用 `cout` 输出了每个字符。需要注意的是,`it` 是一个迭代器,需要通过 `*it` 来访问迭代器指向的字符。
c++ string可以用迭代器吗
是的,C++中的string类提供了迭代器来遍历字符串中的字符。
你可以使用begin()和end()成员函数来获取字符串的起始和结束迭代器,然后使用迭代器进行遍历。例如,以下代码演示了如何使用迭代器遍历一个字符串并打印每个字符:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
// 使用迭代器遍历字符串并打印每个字符
for (auto it = str.begin(); it != str.end(); ++it) {
std::cout << *it;
}
return 0;
}
```
输出结果为:
```
Hello, world!
```
在这个例子中,我们使用了auto关键字来自动推断迭代器类型,通过*it来访问迭代器指向的字符。