STL:string获取字符串元素:[]和at()

字符串中元素的访问是允许的,一般可使用两种方法访问字符串中的单一字符:下标操作符[] 和 成员函数at()。

两者均返回指定的下标位置的字符。第 1 个字符索引(下标)为 0,最后的字符索引(下标)为 length()-1。

使用 []

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;


int main()
{
	string s1 = "asdfghjkl";

	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " ";
	}
	cout << endl;

	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1.at(i) << " ";
	}
	cout << endl;

	//区别: []方式,如果访问越界,直接崩
	//at方法,访问越界,抛出异常 Out_of_range
	try {
		cout << s1[100] << endl;
		//cout << s1.at(100) << endl;
	}
	catch (...)//捕获所有异常
	{
		cout << "越界" << endl;
	}

	return 0;
}


使用at()

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;


int main()
{
	string s1 = "asdfghjkl";

	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " ";
	}
	cout << endl;

	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1.at(i) << " ";
	}
	cout << endl;

	//区别: []方式,如果访问越界,直接崩
	//at方法,访问越界,抛出异常 Out_of_range
	try {
		//cout << s1[100] << endl;
		cout << s1.at(100) << endl;
	}
	catch (...)//捕获所有异常
	{
		cout << "越界" << endl;
	}

	return 0;
}

可以看出两者区别:

  1.   [ ]方式,如果访问越界,直接崩
  2.   访问越界,抛出异常 out_of_range
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章