/**
* C++ 标准库中提供了string类型专门表示字符串
* #include<string>
* using namespace std;
*
* 使用string可以更为方便和安全的管理字符串
*
*/
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
/* code */
string s1; //空字符串
string s2 = "helloworld"; // 定义并初始化
string s3("helloworld");
string s4 = string("helloworld");
cout<<s4<<endl;
// 获取字符串的长度
cout<<s4.length()<<endl;
cout<<s4.size()<<endl; // 本质上和上面一样
cout<<s4.capacity()<<endl;
// 字符串的比较 == != >= > <= <
string s5 = "world";
cout<<"s1==s2 "<<(s1==s5)<<endl;
cout<<"s1!=s2 "<<(s1!=s2)<<endl;
// 转还为C风格的字符串
const char* cc_str1 = s1.c_str();
char* name = "000";
char names[] = "jack";
cc_str1 = name;
cout<<"cc_str1 "<<cc_str1<<endl;
cc_str1 = "dad";
//cc_str1[0] = 'l';
names[0] = 'l';
cout<<"names "<<names<<endl;
// 随机访问(获取字符串中某个字符)[]
string s6 = "hello";
cout<<s6[0]<<endl;
s6[0] = 'd';
cout<<s6<<endl;
// 字符串拷贝: =
string s7 = "hello";
string s8 = s7;
cout<<s8<<endl;
// 字符串连接 + +=
string s9 = "hello";
string s10 = "lucky";
cout<<s9+s10<<endl;
return 0;
}
输出如下:
1 warning generated.
helloworld
10
10
22
s1==s2 0
s1!=s2 1
cc_str1 000
names lack
h
dello
hello
hellolucky