字符串的本质就是字符数组,字符数组和字符串都可以作为存放字符的数组,所以可以通过数组的下标访问每一个字符。
区别:字符数组的长度就是字符的总长度,而字符串会+1,是因为包含了最后的“\0”结束符。
三种方式访问字符串
#1.字符数组
char str1[] = "hello world!";
cout << str1 << endl; //"hello world!"
cout << str1[0] << endl; //h
cout << str1[1] << endl; //e
#2.字符串变量
string str2 = "hello world!";
cout << str2 << endl; //"hello world!"
cout << str2[0] << endl; //cout为h
cout << str2[1] << endl; //cout为e
#3.字符常量指针
const char* str3 = "hello world";
cout << str3 << endl; //"hello world!"
cout << str3[0] << endl; //cout为h
cout << str3[1] << endl; //cout为e
说一下容易困惑的地方,比如下方代码,输出的是指针数组的数组名,按理说指针数组里存放的都是地址,怎么就输出成了字符串里的内容呢?为什么可以直接使用字符串赋值给指针呢?
//这里的const 由于编译器版本的不同,我是不建议省略的,
//const 放在指针前,指针的指向可以变,指向地址的值不能变,字符串常量是存放在全局区中的常量区嘛,常量当然不能改变它的值。
const char* names[4] = {
"Zara",
"Hina",
"Nuha",
"Sara"
};
for (int i = 0; i < 4; i++)
{
cout << names[i] << endl; //Zara、Hina、Nuha、Sara
//指针数组嘛。数组里存放的都是指针,每个指针指向每个字符串的首地址,解引用后就是每个字符串的第一个字符啦
cout << *names[i] << endl; //Z、H、N、S
}
“Zara”,用“”括起来后,会返回地址,同时在字符串的最后加上“\0”结束符。由于c++的会对<<操作符进行重载,这里我们看到字符指针,会把指针名当成字符串名。