转换到C样式数组

来源:互联网 发布:ip mac 扫描工具 编辑:程序博客网 时间:2024/06/06 02:58
char& string::operator[] (size_type nIndex)const char& string::operator[] (size_type nIndex) constBoth of these functions return the character with index nIndexPassing an invalid index results in undefined behaviorUsing 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 arraySample code:string sSource("abcdefg");cout << sSource[5] << endl;sSource[5] = 'X';cout << sSource << endl;Output:fabcdeXg

还有一个非算子的版本。这个版本是慢因为它使用异常来检查如果nIndex是有效的。如果你不确定是否是有效的索引你应该使用此版本访问数组
Sample code:string sSource("abcdefg");cout << sSource.at(5) << endl;sSource.at(5) = 'X';cout << sSource << endl;Output:fabcdeXg

转换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 buffercout << szBuf << endl;Output:black


0 0