首页 > 技术文章 > STL之string

Bravewtz 2019-01-27 11:02 原文

 1 #include<iostream>
 2 #include<vector>
 3 #include<algorithm>//常用算法头文件
 4 using namespace std;
 5 
 6 //string与char*的相互转换
 7 void test03(){
 8     //string转为char*
 9     string str="1111";
10     const char* s=str.c_str();
11     cout<<s<<endl;
12 
13     //char*转为string
14     const char* ss="1111";
15     string sstr=s;
16     cout<<sstr<<endl;
17 }
18 
19 //拼接操作
20 void test04(){
21     string s="abcd";
22     string s2="111";
23     s+="abcd";
24     s+=s2;
25 
26     cout<<s2<<endl;
27 
28     string s3="2222";
29     s2.append(s3);
30     cout<<s2<<endl;
31 
32 
33 }
34 
35 //查找操作
36 void test05(){
37     string s="abcdefghifgjk";
38     int pos =s.rfind("fg");
39     cout<<"pos:"<<pos<<endl;
40 }
41 
42 //替换操作
43 void test06(){
44     string s="abcdefg";
45     s.replace(0,2,"111");
46     cout<<s;
47 }
48 
49 //比较操作
50 void test07(){
51     string s1="abcd";
52     string s2="abce";
53     if(s1.compare(s2)==0){
54         cout<<"字符串相等"<<endl;
55     }
56     else{
57         cout<<"字符串不相等"<<endl;
58     }
59 }
60 
61 
62 //截取字符串
63 void test08(){
64     string s="abcdefg";
65     string substring_s=s.substr(2,3);
66     //从第二个位置开始,截取三个字符
67     cout<<substring_s<<endl;
68 }
69 
70 //插入和删除
71 void test09(){
72     string s="abcdefg";
73     s.insert(3,"111");
74     cout<<s<<endl;
75     s.erase(0,2);
76     cout<<s<<endl;
77 
78 }
79 
80 
81 int main()
82 {
83 
84     test09();
85 
86     return 0;
87 }

 

推荐阅读