文章目录
一、string 字符串遍历
1、string 字符串遍历方法
string 字符串遍历方法 :
- 使用 下标 遍历字符串 : 字符串可以像数组那样使用下标遍历 , 有两种方式 , 一种是使用重载的
[]
操作符 , 另一种就是使用at()
函数 ; - 使用 迭代器 遍历字符串 : 使用
string::iterator
迭代器遍历字符串 ;
2、使用 数组下标 [] 遍历字符串
使用 数组下标 遍历字符串 , 主要调用 operator[]
运算符重载函数 实现 ’
在 C++ 的 std::string
类中 , operator[]
函数 是一个成员函数 , 这是一个运算符重载函数 ,
它用于访问字符串中的特定字符 , 这个函数接受一个整数参数 n , 表示要访问的字符的位置 ;
operator[]
函数的 函数原型如下 :
char& operator[] (int n);
该函数返回一个字符引用 , 表示字符串中位置为 n 的字符 ;
特别注意 : 该函数返回的是 字符的引用 , 因此可以直接用于 访问和修改 字符串中的字符 ;
代码示例 :
string s1 = "123456789";
// I. 使用数组方式遍历 string 字符串
cout << "使用数组方式遍历 string 字符串 : ";
for (int i = 0; i < s1.length(); i++)
{
// 输出 string 字符串中的单个 字符元素
cout << s1[i] << " ";
}
// 输出回车换行
cout << endl;
3、使用 at() 函数 遍历字符串
在 C++ 语言中的 std::string
类中 , 定义了一个成员函数 at()
函数 , 用于访问字符串中特定位置的字符 ; 该函数接受一个整数参数 n , 表示要访问的字符的位置 ;
at()
函数原型如下 :
const char& at(size_t pos) const;
at()
函数返回一个常量字符引用 , 表示字符串中位置为 pos
的字符 ;
与 operator[]
运算符重载函数不同 , at()
函数在访问超出字符串范围的索引时会抛出 std::out_of_range
异常 ;
代码示例 : 下面的代码中 , 故意增加 1 字节, 令其抛出 std::out_of_range
异常 ;
string s1 = "123456789";
// III. 使用 at() 函数遍历 string 字符串
cout << "使用 at 函数遍历 string 字符串 : ";
try
{
// 此处故意增加 1 字节, 令其抛出异常
for (int i = 0; i < s1.length() + 1; i++)
{
// 输出 string 字符串中的单个 字符元素
// at 函数如果越界 会 抛出异常
cout << s1.at(i) << " ";
}
// 输出回车换行
cout << endl;
}
catch ( ... )
{
cout << "出现异常" << endl;
}
4、使用 string::iterator 迭代器 遍历字符串
首先 , 调用 string
类的 begin()
函数 , 获取迭代器 , 其可以理解为是指向元素的指针 ;
std::string::iterator it = str.begin();
然后 , 对迭代器进行自增操作 , 即可访问下一个元素的地址 ;
it++
最后 , 调用 string
类的 end()
函数 , 获取迭代器的最后一个元素地址 , 判断 迭代器 的指针地址 是否是 该地址 ,
it != s1.end()
代码示例 :
string s1 = "123456789";
// II. 使用 迭代器 遍历 string 字符串
cout << "使用 迭代器 遍历 string 字符串 : ";
for (string::iterator it = s1.begin(); it != s1.end(); it++)
{
// 输出 string 字符串中的单个 字符元素
cout << *it << " ";
}
// 输出回车换行
cout << endl;
5、代码示例 - string 字符串遍历
代码示例 :
#include "iostream"
using namespace std;
#include "string"
int main() {
string s1 = "123456789";
// 遍历 string 字符串
// I. 使用数组方式遍历 string 字符串
cout << "使用数组方式遍历 string 字符串 : ";
for (int i = 0; i < s1.length(); i++)
{
// 输出 string 字符串中的单个 字符元素
cout << s1[i] << " ";
}
// 输出回车换行
cout << endl;
// II. 使用 迭代器 遍历 string 字符串
cout << "使用 迭代器 遍历 string 字符串 : ";
for (string::iterator it = s1.begin(); it != s1.end(); it++)
{
// 输出 string 字符串中的单个 字符元素
cout << *it << " ";
}
// 输出回车换行
cout << endl;
// III. 使用 at() 函数遍历 string 字符串
cout << "使用 at 函数遍历 string 字符串 : ";
try
{
// 此处故意增加 1 字节, 令其抛出异常
for (int i = 0; i < s1.length() + 1; i++)
{
// 输出 string 字符串中的单个 字符元素
// at 函数如果越界 会 抛出异常
cout << s1.at(i) << " ";
}
// 输出回车换行
cout << endl;
}
catch ( ... )
{
cout << "出现异常" << endl;
}
// 控制台暂停 , 按任意键继续向后执行
system("pause");
return 0;
};
执行结果 :
使用数组方式遍历 string 字符串 : 1 2 3 4 5 6 7 8 9
使用 迭代器 遍历 string 字符串 : 1 2 3 4 5 6 7 8 9
使用 at 函数遍历 string 字符串 : 1 2 3 4 5 6 7 8 9 出现异常
请按任意键继续. . .