我是靠谱客的博主 帅气小懒虫,这篇文章主要介绍字符串的一些操作,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
=,assign() //赋以新值 s.assign(str); s.assign(str,1,3);//如果str是”iamangel” 就是把”ama”赋给字符串 s.assign(str,2,string::npos);//把字符串str从索引值2开始到结尾赋给s s.assign(“gaint”); s.assign(“nico”,5);//把’n’ ‘I’ ‘c’ ‘o’ ‘’赋给字符串 s.assign(5,’x’);//把五个x赋给字符串 b) swap() //交换两个字符串的内容 c) +=,append(),push_back() //在尾部添加字符 d) insert() //插入字符 e) erase() //删除字符 g) replace() //替换字符 h) +//串联字符串 ==,!=,<,<=,>,>=,compare() //比较字符串 string s(“abcd”); s.compare(“abcd”); //返回0 s.compare(“dcba”); //返回一个小于0的值 s.compare(“ab”); //返回大于0的值 s.compare(s); //相等 s.compare(0,2,s,2,2); //用”ab”和”cd”进行比较 小于零 s.compare(1,2,”bcx”,2); //用”bc”和”bc”比较。 j) size(),length() //返回字符数量 r) copy() //将某值赋值为一个C_string s) c_str() //将内容以C_string返回 u) substr() //返回某个子字符串 s.substr(11);//从索引11往后的子串 s.substr(5,6);//从索引5开始6个字符 k)find() string::size_type position; position = s.find("xx"); //查找s 中flag 出现的所有位置。 flag="a"; position=0; while((position=s.find_first_of(flag,position))!=string::npos) { //position=s.find_first_of(flag,position); cout<<"position : "<<position<<endl; position++; }

字符串的详细操作,以及示范
这篇也不错,可以看看
stringstream常见用法介绍
string str.substr(nStart) //默认 从str字符串nStart位置开始截取到str结束为止

string str.substr(nStart, nLength) // 从str字符串nStart位置开始截取nLength个字符!如果nLength>剩余的字符则截取到str结束为止

举例:

string str(“12345asdf”);

string strTmp1= str.substr(1); //获得字符串str中 从第1位开始到结束的字符串,strTmp1值为:“23456asdf”,默认到结束位置
string strTmp2 = str.substr(1,5); //获得字符串s中 从第1位开始的长度为5的字符串,strTmp1值为:“23456”

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// string::substr #include <iostream> #include <string> int main () { std::string str="We think in generalities, but we live in details."; // (quoting Alfred N. Whitehead) std::string str2 = str.substr (3,5); // "think" std::size_t pos = str.find("live"); // position of "live" in str std::string str3 = str.substr (pos); // get from "live" to the end std::cout << str2 << ' ' << str3 << 'n'; return 0; }
复制代码
1
2
3
Output think live in details.

样例来源

最后

以上就是帅气小懒虫最近收集整理的关于字符串的一些操作的全部内容,更多相关字符串内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部