1 当把string对象和字符字面值及字符串字面值混在一条语句中使用时,必须确保每个加法运算符(+)的两侧对象至少有一个是string
1 当把string对象和字符字面值及字符串字面值混在一条语句中使用时,必须确保每个加法运算符(+)的两侧对象至少有一个是string
string s1=“hello”;
string s2=s1 + " , "; //正确:把string对象和一个字面值相加
string s5="hello" + ","; //错误:两个运算对象都不是string
2 涉及到字符串大小写转换,字符是否包含空白......需要用到头文件cctype
以下为字符函数库中常用的函数:
3 使用for处理字符串中的每一个字符
int main() { string str("some string"); for (auto c : str) cout << c << endl; //逐一输出字符 }
4 使用for改变字符串中的字符
int main()
{
string str("some string");
for (auto &c : str)
c = toupper(c); //c是一个引用
cout << str << endl;
}
5 只处理一部分字符
int main()
{
string str("some string");
if (!str.empty())
str[0] = toupper(str[0]);
cout << str << endl;
}
使用下标进行迭代
int main()
{
string s("some string");
for (decltype(s.size()) index = 0; index != s.size()&& !isspace(s[index]); ++index)
s[index] = toupper(s[index]);
cout << s << endl;
}