03-字符串存取
F.3 字符串存取
有4种方法可以访问各个字符,其中两种方法使用[ ]运算符,另外两种方法使用at()方法:
reference operator[](size_type pos);
const_reference operator[](size_type pos) const;
reference at(size_type n);
const_reference at(size_type n) const;
第一个operator 方法使得能够使用数组表示法来访问字符串的元素,可用于检索或更改值。第二个operator 方法可用于const对象,但只能用于检索值:
string word("tack");
cout << word[0]; // display the t
word[3] = 't'; // overwrite the k with a t
const ward("garlic");
cout << ward[2]; // display the r
at()方法提供了相似的访问功能,只是索引是通过函数参数提供的:
string word("tack");
cout << word.at(0); // display the t
差别在于(除语法差别外):at()方法执行边界检查,如果pos>=size(),将引发out_of_range异常。pos的类型为size_type,是无符号的,因此pos的值不能为负;而operator 方法不进行边界检查,因此,如果pos>=size(),则其行为将是不确定的(如果pos= =size(),const版本将返回空值字符的等价物)。
因此,可以在安全性(使用at()检测异常)和执行速度(使用数组表示)之间进行选择。
还有一个这样的函数,它返回原始字符串的子字符串:
basic_string substr(size_type pos = 0, size_type n = npos) const;
它返回一个字符串——这是从pos开始,复制n个字符(或到字符串尾部)得到的。例如,下面的代码将pet初始化为“donkey”:
string message("Maybe the donkey will learn to sing.");
string pet(message.substr(10, 6));
C++11新增了如下四个存取方法:
const charT& front() const;
charT& front();
const charT& back() const;
charT& back();
其中front()方法访问string的第一个元素,相当于operator[] (0);back()方法访问string的最后一个元素,相当于operator[] (size() - 1)。