算法笔记03--字符串01
发布日期:2021-05-08 15:59:53 浏览次数:22 分类:精选文章

本文共 1574 字,大约阅读时间需要 5 分钟。

1.字符串的构造

string s0="hello world"string s1(s0);				//s1拷贝s0string s2(s0,8,3);			//s2从s0下标第8号开始拷贝3位,s2="rld"string s3("hello world");	//s3拷贝字符串string s4("hello world",5);	//s4拷贝hello world前5位string s5(10,'s');			//s5拷贝10个s

2.字符串的操作

2.1 字符串的插入:

string s1="to be question";	string s2="that is a";	string s3="or not world";	string s4;		s4.insert(0,s1);		//在s4的0号位置插入s1,s4="to be question"	s4.insert(6,s3,0,7);  	//在s4的6号位置插入s3从0号位置到7号位置的字符串,s4="to be or not question" 	s4.insert(13,"to be"); 	//在s4的13号位置插入字符串"to be",s4="to be or not te be question"	s4.insert(19,s2);		//在s4的19号位置插入字符串s2,s4="to be or not to be that is a question"

总结:

s.insert(在s中插入位置,待插入字符串s1,s1起始位置(可以省略),s1结束位置(可以省略))

2.2 字符串的移除:

s4.erase(19);	//从s4的19号位置到结束位置移除字符串,s4="to be or not to be"s4.erase(0,9);	//从s4的0号位置到9号位置移除字符串,s4="not to be"  s4.clear();		//清空字符串

总结:

s.erase(起始位置,结束位置(可以省略))

2.3 字符串的操作

string str1="to be";string str2="not to be";string str3=" that is a question";string str=str1+",";				//str="to be,"str=str+str2+";";					//str="to be,not to be;"str+=str3;							//str="to be,not to be;that is a question"

2.4 字符串的函数

string s1="hello world,bye world";int length=s1.size();		   		//返回字符串的长度int position1=s1.find("world");  	//返回待查找字符串起始位置int position2=s1.find("world",10)	//从s1的10号位置开始查找待查找字符串int position3=s1.find('l');			//返回待查找字符起始位置int position4=s1.find('l');   		//从s1的10号位置开始查找待查找字符string s2=s1.substr(13);			//从s1的13号位置开始截取字符串赋值给s2,s2="e world"string s3=s1.substr(13,3);			//从s1的13号位置开始截取3个字符赋值给s2,s2="e w"

总结:

s.find(待查找字符串(字符),待查找起始位置(可省略)) //返回第一次查找到位置
s.substr(截取起始,截取数目) //返回截取字符串

上一篇:算法笔记04--字符串02
下一篇:算法笔记02--排序算法

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年04月01日 02时53分09秒