string类有begin和end迭代器吗
时间: 2024-01-14 19:05:01 浏览: 28
是的,`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` 来访问迭代器指向的字符。
相关问题
string类有迭代器吗
是的,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
```
std::string有迭代器吗
是的,std::string有迭代器。可以使用begin()和end()函数获取迭代器,也可以使用auto关键字自动推导迭代器类型,例如:
```c++
std::string str = "hello world";
// 使用迭代器遍历字符串
for (auto it = str.begin(); it != str.end(); ++it) {
std::cout << *it << " ";
}
// 使用range-based for循环遍历字符串
for (char c : str) {
std::cout << c << " ";
}
```
输出结果为:
```
h e l l o w o r l d
h e l l o w o r l d
```