string用法合集

\(string\) 用法:

使用索引访问:

string s = "123123123";

\(s[0] = 1,s[1] = 2 \cdots\)

可以直接用运算符比较:

string s1 = "asd";
string s2 = "dsa";
return s1 < s2;
//按字典序来,结果应该返回的是 true

字符串排序:

string s = "1b3rdc871yvbv";
sort(s.begin(),s.end());
cout<<s;
//输出结果应该是:“11378bbcdrvvy”

\(size() , length()\) 函数:

string s = "1b3rdc871yvbv";
cout<<s.size();
cout<<' ';
cout<<s.length();

输出结果:

13
13

查找字符串中的字母:

\(find()\)函数 。

\(find(ch , startpos)\)

查找并返回从 \(startpos\) 位置开始的字符 \(ch\) 的位置(第一次出现的)。

如果查找不到,返回 \(-1\)

string s = "abcdefghi";
cout<<int(s.find("a"));
cout<<" ";
cout<<int(s.find("k"));

输出结果:
0 -1

截取字符串:

\(substr()\) 函数

\(substr(start , len)\) :

从字符串的 \(start\) 位置开始,截取长度为 \(len\) 的字符串。
(省去 \(len\) 参数时自动截取到字符串的末尾)

string s = "asdfghjkl";
string s1 = s.substr(0,4);
cout<<s1;

输出结果:
asdf

字符串的添加函数:\(append()\)

\(append(s)\):将字符串 \(s\) 添加到字符串的末尾。

\(append(s, pos, n)\):将字符串 \(s\) 中,从 \(pos\) 开始的 \(n\) 个字符添加到字符串的末尾。

string s = "asdasdasd";
string s1 = "1919810";
string s2 = "wyl123ly";
s1.append(s);
s2.append(s,3,3);
cout<<s1<<" "<<s2;

输出结果:
1919810asdasdasd wyl123lyasd

字符串中的删除函数:

\(replace()\) 函数

\(replace(pos, n, s)\)
删除字符串从 \(pos\) 开始的 \(n\) 个字符,然后在 \(pos\) 处插入串 \(s\)

string s = "114514";
string s1 = "asdsdfdfg";
s.replace(2,3,s1);
cout<<s;

输出结果:
11asdsdfdfg4

\(erase()\) 函数

\(erase(pos, n)\)
删除从 \(pos\) 开始的 \(n\) 个字符。

string s = "wyl123ly";
s.erase(2,2);
cout<<s;

输出结果:
wy23ly

字符串中插入函数:\(insert()\)

\(insert(pos, s)\): 在 \(pos\) 位置插入字符串 \(s\)

string s = "wyl114514";
string s1 = "nihao";
s.insert(2,s1);
cout<<s;

输出结果:
wynihaol114514


\(END\)

posted @ 2023-10-14 10:19  wyl123ly  阅读(56)  评论(0)    收藏  举报