转换到C样式数组

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值