char& string::operator[] (size_type nIndex)
const char& string::operator[] (size_type nIndex) const
Both of these functions return the character with index nIndex
Passing an invalid index results in undefined behavior
Using length() as the index is valid for const strings only, and returns the value generated by the string’s default constructor. It is not recommended that you do this.
Because char& is the return type, you can use this to edit characters in the array
Sample code:
string sSource("abcdefg");
cout << sSource[5] << endl;
sSource[5] = 'X';
cout << sSource << endl;
Output:
f
abcdeXg
还有一个非算子的版本。这个版本是慢因为它使用异常来检查如果nIndex是有效的。如果你不确定是否是有效的索引,你应该使用此版本访问数组:
Sample code:
string sSource("abcdefg");
cout << sSource.at(5) << endl;
sSource.at(5) = 'X';
cout << sSource << endl;
Output:
f
abcdeXg
转换到C样式数组
多功能(包括所有的C函数)预计,字符串被格式化为C风格字符串而不是std::string。为此,std::string提供了3种不同的方式来转换std::字符串C风格字符串。
Sample code:
string sSource("sphinx of black quartz, judge my vow");
char szBuf[20];
int nLength = sSource.copy(szBuf, 5, 10);
szBuf[nLength]='\0'; // Make sure we terminate the string in the buffer
cout << szBuf << endl;
Output:
black