C++ string常用操作

目录

1.获取字符串长度

2.字符串比较原理

3.拼接(+)

4.添加(append)

5.插入(insert)

6.删除(erase)

7.剪切(substr)


1.获取字符串长度

string str = "1234567";
int len = str.length();//len=7


2.字符串比较原理

①两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止,如"15">"123"。
②若是遇到‘\0’结束比较,则长的子串大于短的子串,如:“9856” > “985”。

3.拼接(+)

string str1 = "hello";
string str2 = "world";
str1 = str1 + " " + str2;//str1="hello world"


4.添加(append)

append函数在字符串的末尾添加字符串。

string str1 = "hello";
string str2 = "world";
str1.append(" " + str2);//str1="hello world"


5.插入(insert)

string str = "hello world";
string str2 = "hard ";
string str3 = "it is so happy wow";
 
//s.insert(pos,n,ch)        在字符串s的pos位置上面插入n个字符ch
str.insert(6,4,'z');        // str = "hello zzzzworld"
 
//s.insert(pos,str)         在字符串s的pos位置插入字符串str
str.insert(6,str2);         // str = "hello hard world"
 
//s.insert(pos,str,a,n)     在字符串s的pos位置插入字符串str中位置a到后面的n个字符
str.insert(6,str3,6,9);     // str = "hello so happy world"
 
//s.insert(pos,cstr,n)      在字符串s的pos位置插入字符数组cstr从开始到后面的n个字符
//此处不可将"it is so happy wow"替换为str3
str.insert(6,"it is so happy wow",6);       // str = "hello it is world"


6.删除(erase)

//erase(index,n)从下标index开始删除n个字符
string str = "01234567";
str.erase(3, 2);//str="012567"


7.剪切(substr)

string tmp;
调用substr的字符串不改变
//①substr(index,n)从下标index开始截取n个字符
string str1 = "0123456789";
tmp=str1.substr(6, 2);//tmp="67"  str1 = "0123456789"
//②substr(index)从下标index开始截取字符至字符串结束
string str2 = "0123456789";
tmp=str2.substr(7);//tmp="789"    str2 = "0123456789"
 


 

发布了117 篇原创文章 · 获赞 52 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ZhaDeNianQu/article/details/103990392