我是Zac,是一名xxs,有时也是一名程序员(👈🏼著名开张白)今天我们来说一下string的几个函数:
append()函数:
将两个字符串拼接在一起(字符串一 += 字符串二也是可以的):
#include <iostream>
using namespace std;
int main() {
string a = "优快云";
string b = ".net";
a.append(b);
//a += b;
cout << a << endl;
return 0;//别忘啦!
}
输出的是"youkuaiyun.com"。
substr()函数:
简单梳理一下substr()函数括号里参数的意义↓(记住了,我被它坑过!)
#include <iostream>
using namespace std;
int main() {
string s = "youkuaiyun.com_is_good";
s = s.substr(0, 8);
//s = s.substr(截取开始下标, 截取字符串长度);("s ="别忘啦!)
cout << s << endl;
return 0;
}
输出"youkuaiyun.com"。
insert()函数:
功能:将a插入b。↓
#include <iostream>
using namespace std;
int main() {
string s = "CN.net";
s.insert(1, "SD");
//s.insert(插入位置下标, 插入字符串);
cout << s << endl;
return 0;
}
输出"youkuaiyun.com"。
find()函数:
话不多说,解释一下功能:查找一个字符串是否存在于另一个字符串 ↓
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "youkuaiyun.com";
string a = "SD";
if (s.find(a) != string::npos) {
cout << s.find(a) << endl;
} else {
cout << -1 << endl;
}
//cout << (int)s.find(a) << endl;(这种方法和上面的代码实现的效果是一样的)
return 0;
}
输出"1"。
实战:
下面来一道题试试手吧:
题目传送门:https://www.luogu.com.cn/problem/P5734
题目描述
你需要开发一款文字处理软件。最开始时输入一个字符串作为初始文档。可以认为文档开头是第 0 0 个字符。需要支持以下操作:
输入1 str:后接插入,在文档后面插入字符串 str str,并输出文档的字符串;
输入2 a b:截取文档部分,只保留文档中从第 a 个字符起 b 个字符,并输出文档的字符串;
输入 a str:插入片段,在文档中第a 个字符前面插入字符串 str,并输出文档的字符串;
输入4 str:查找子串,查找字符串str 在文档中最先的位置并输出;如果找不到输出 − 1。 为了简化问题,规定初始的文档和每次操作中的 str 都不含有空格或换行。最多会有 q 次操作。
输入格式
第一行输入一个正整数 q,表示操作次数。 第二行输入一个字符串 str,表示最开始的字符串。 第三行开始,往下 q 行,每行表示一个操作,操作如题目描述所示。 输出格式 一共输出 q 行。 对于每个操作 1 , 2 , 3,根据操作的要求输出一个字符串。 对于操作 4,根据操作的要求输出一个整数。
输入输出样例
4
ILove
1 Luogu
2 5 5
3 3 guGugu
4 gu
ILoveLuogu
Luogu
LuoguGugugu
3
这道题是一道水题(如果你前面的看懂了话),话不多说,上代码!
AC代码:
#include <iostream>
#include <string>
using namespace std;
int q, b, c, a;
string s, str, t;
int main() {
cin >> q;
cin >> s;
for (int i = 1; i <= q; i++) {
cin >> a;
if (a == 1) {
cin >> str;
s.append(str);
//s = s + str;
cout << s << endl;
}
if (a == 2) {
cin >> b >> c;
t = s.substr(b, c);
s = t;
cout << s << endl;
}
if (a == 3) {
cin >> b >> str;
s.insert(b, str);
cout << s << endl;
}
if (a == 4) {
cin >> str;
if (s.find(str) != string::npos) {
cout << s.find(str) << endl;
} else {
cout << "-1" << endl;
}
//cout << (int)s.find(str) << endl;
}
}
return 0;
}
(我所有的文章都是免费公开的,给个赞👍🏼,关注✅,收藏📂一下呗🙏🏼(毕竟人家可是写了1921个字呢)) ……