#include <iostream>
#include <string>
int main()
{
const std::string cS ("c.biancheng.net");
std::string s ("abode");
char temp =0;
char temp_1 = 0;
char temp_2 = 0;
char temp_3 = 0;
char temp_4 = 0;
char temp_5 = 0;
temp = s [2]; //"获取字符 'c'
temp_1 = s.at(2); //获取字符 'c'
temp_2 = s [s.length()]; //未定义行为,返回字符'\0',但Visual C++ 2012执行时未报错
temp_3 = cS[cS.length()]; //指向字符 '\0'
temp_4 = s.at (s.length ()); //程序异常
temp_5 = cS.at(cS.length ()); //程序异常
std::cout << temp <<temp_1 << temp_2 << temp_3 << temp_4 << temp_5 << std::endl;
return 0;
}
通过对上述代码的分析可知,要理解字符串的存取需要多实践、多尝试,并且要牢记基础知识和基本规则。
#include <iostream>
#include <string>
int main()
{
std::string s ("abode");
std::cout << s << std::endl ;
char& r = s[2] ; //建立引用关系
char*p=&s[3]; //建立引用关系
r='X' ;//修改内容
*p='Y' ;//修改内容
std::cout << s << std::endl; //输出
s = "12345678"; //重新赋值
r ='X'; //修改内容
*p='Y'; //修改内容
std::cout << s << std::endl; //输出
return 0;
}
程序输出结果为:
abode
abXYe
12XY5678
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有