string对元素的访问函数
- string::operator[]有两种:
char& operator[] ( size_t pos ) //返回pos位置元素,非const类调用
const char& operator[] ( size_t pos ) const //返回pos位置元素,const类调用
- string::at和operator[]的用法类似
char& at (size_t pos); //返回pos位置元素,非const类调用
const char& at (size_t pos) const; //返回pos位置元素,const类调用
- back()返回字符串的最后一个字符的引用(C++11)
用法:
char& back();
const char& back() const;
描述:
Returns a reference to the last character of the string.
This function shall not be called on empty strings.
- front()返回字符串的第一个字符的引用,不同于begin方法(C++11)
用法:
char& front();
const char& front() const;
描述:
Returns a reference to the first character of the string.
Unlike member string::begin, which returns an iterator to this same character, this function returns a direct reference.
This function shall not be called on empty strings.
代码:
/*
>Plan:string元素的访问
>Author:ADiiana
>Time:2019/03/17
*/
#include<iostream>
#include<string>
using namespace std;
int main(){
string str("test string");
const string const_str("abcdef");
cout << "========string::operator===========" << endl;
for (size_t i = 0; i < str.length(); ++i)
{
str[i] = str[i] - 'a' + 'A';
cout << str[i];
}
cout << endl;
cout << "========string::at()===========" << endl;
for (unsigned i = 0; i<str.length(); ++i)
{
std::cout << str.at(i);
}
cout << endl;
//编译错误,不能给常量赋值
/*for (size_t i = 0; i < const_str.length(); ++i)
{
const_str[i] = const_str[i] - 'a' + 'A';
cout << const_str[i];
}*/
str.back() = '!';
cout << str << endl;
str.front() = 't';
cout << str << endl;
system("pause");
return 0;
}