C++ 与String有关的函数!!!

String函数

1.字符串的输入

(1)
string s;
cin >> s;//碰到空格等分隔符会终端输入

/*
string s;
cin >> s;//如果输入 hello world
cout << s;//输出的是hello
*/

(2)

string s;
getline(cin, s);//获取一行,可以带空格
cout << s;

2.erase函数(删除)

**删除 **某一个元素(还有其他用法的erase,但是还没学我就先不给你总结,到时候讲了我补充上去!)
//example

#include <string>//要有这个头文件

string s = "012345";
s.erase(2, 3);//意思是从下标为2的元素开始,删除 三个元素
cout << s;//输出结果为015
3.substr函数(替换)
//example

#include <string>//要有这个头文件

string s = "012345";
s = s.substr(1, 3);//意思是从下标为1的元素开始,往后数三个替换原来的字符串s
cout << s;//输出结果为123
4.insert函数(插入)
//example

#include <string>//要有这个头文件

string s = "0123";
s.insert(2, "haha");//把haha这个字符串插入到字符串s的下标为2的地方
cout << s;//输出为01haha23
5.replace函数(取代)
//example

#include <string>

string s = "012345";
//从字符串s的下标为2的元素开始往后数4个,将这些元素替换为ab
s.replace(2, 4, "ab");
cout << s;//输出为01ab
6.string可以用 + 和 = 运算符
+运算
//example

#include <string>

string s1 = "12";
string s2 = "ab";
cout << s1 + s2 << endl;//输出结果为12ab
cout << s2 + s1 << endl;//输出结果为ab12
=运算
#include <string>

string s1 = "12";
string s2 = "ab";
s2 = s1;
cout << s2 << endl;//输出结果为12
7.length函数(求字符串长度)
#include <string>

string s = "abcd";
int c = s.length();
cout << c << endl;//输出结果为4,为字符串s的长度
8.find函数(查找字符串,返回下标)
#include <string>

string s1 = "abcde";
string s2 = "cde";
int c = s1.find(s2);//查找字符串s2是否可以在字符串中找到,找到的话返回s2首个元素在s1中的下标

cout << c << endl;//输出结果为2,是字符串“cde”的首个元素在字符串s中的下标
原文地址:https://www.cnblogs.com/scl0725/p/12372404.html