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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章