1 #include <iostream>
2 #include <cstring>
3 #include <string>
4
5 using namespace std;
6
7 int main()
8 {
9 //直接赋值
10 string test;//定义了一个空字符串str
11 test = "test_the_string";
12
13 cout << "——————string字符串截取————————" << endl;
14
15 //利用已有string初始化
16 string s1(test); //复制字符串,s1=test,深拷贝
17 cout << "s1 - " << s1 << endl;
18
19 string s2(test, 6);//s2=test[6:]
20 cout << "s2 - " << s2 << endl;
21
22 string s3(test, 6, 3);//s3=test[6:(6+3)]
23 cout << "s3 - " << s3 << endl;
24
25 string s3_(test.begin()+6,test.begin()+9); //s3=test[6:(6+3)]
26 cout << "s3_ - " << s3_ << endl;
27
28 cout << "——————字符串数组截取————————" << endl;
29
30 // C风格字符串转string初始化
31 char testC[] = "test_the_string"; //定义了一个C字符串
32
33 string s4(testC); //s3=test
34 cout << "s4 - " << s4 << endl;
35
36 string s5(testC,6); //s3=test[:7]
37 cout << "s5 - " << s5 << endl;
38
39 string s6(5,'A'); //生成一个字符串,包含5个'A'字符
40 cout << "s6 - " << s6 << endl;
41
42 cout << "——————字符串比较操作符————————" << endl;
43 /* ==、>、<、>=、<=、和!=比较字符串(自左向右逐个按ASCII值大小相比较)
44 * 可以用+或者+=操作符连接两个字符串,
45 * 并可以用[]获取特定的字符 */
46
47 bool temp = (s1 > "temper");//s>m
48 cout << "s1 > s2 --- " << temp << endl;
49
50 cout << "——————字符串比较操作符————————" << endl;
51 /* string的一些特性
52 int capacity()const; //返回当前容量(即string中不必增加内存即可存放的元素个数)
53 int max_size()const; //返回string对象中可存放的最大字符串的长度
54 int size()const; //返回当前字符串的大小
55 int length()const; //返回当前字符串的长度
56 bool empty()const; //当前字符串是否为空
57 void resize(int len,char c); //把字符串当前大小置为len,多去少补,多出的字符c填充不足的部分*/
58
59 cout << "s1是否为空:" << s1.empty() << endl;
60 cout << "s1的长度为:" << s1.length() << endl;
61 cout << "s1的当前容量(不新分配内存):" << s1.capacity() << endl;
62 cout << "s1的最大容量(重新分配内存):" << s1.max_size() << endl;
63 cout << "s1的长度:" << s1.size() << endl;
64 s1.resize(20, '-');
65 cout << "s1修改长度后,变成了:" << s1 << endl;
66
67 cout << "——————字符串的查找————————" << endl;
68 /* 查询结果类型为string::size_type,没有查询到,则返回string::npos;
69 * 主要函数:find, rfind, find_first_of,find_last_of,s.find_first_not_of */
70
71 cout << "->方法1,使用string::npos判断\n";
72 string::size_type loc;
73 string s = "study hard and make progress everyday! every day!!";
74 loc = s.find("make", 20);
75
76 if(loc != string::npos){ //搜不到为string::npos
77 cout << "在" << loc << "找到" << endl;
78 }
79 else{
80 cout << "没有找到元素" << endl;
81 };
82
83 cout << "->方法2,string::npos可强制转换为-1\n";
84 int local;
85 local = static_cast<int>(s.find("make", 20));
86
87 if(local != -1){ //显式转换为int,搜不到为-1
88 cout << "在- " << local << " -找到元素" << endl;
89 }
90 else{
91 cout << "没有找到元素" << endl;
92 };
93
94 cout << "——————字符串的常用函数————————" << endl;
95
96 cout << s1.erase(2,2) << endl << endl; //【删除】第2个位置的后2个字符,返回删除后的结果
97 cout << s1.insert(2, "st") << endl; //在第2个位置【插入】字符串“st”
98 cout << s1.append("尾部新添加的") << endl; //【append】末尾添加
99 cout << s1.replace(5, 3, "修改值") << endl; //索引5开始的3个字符【替换】成"修改值"
100 cout << s1.substr(1, 4) << endl; //【截取】字符串,s1[1:4]
101
102 return 0;
103 }