string几种操作详解

我是Zac,是一名xxs,有时也是一名程序员(👈🏼著名开张白)今天我们来说一下string的几个函数:

append()函数:

将两个字符串拼接在一起(字符串一 += 字符串二也是可以的):

#include <iostream>
using namespace std;
int main() {
    string a = "CSDN";
    string b = ".net";
    a.append(b);
    //a += b;
    cout << a << endl;
    return 0;//别忘啦!
}

输出的是"CSDN.net"。

substr()函数:

简单梳理一下substr()函数括号里参数的意义↓(记住了,我被它坑过!)

#include <iostream>
using namespace std;
int main() {
    string s = "CSDN.net_is_good";
    s = s.substr(0, 8);
    //s = s.substr(截取开始下标, 截取字符串长度);("s ="别忘啦!)
    cout << s << endl;
    return 0;
}

输出"CSDN.net"。 

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;
}

输出"CSDN.net"。

find()函数:

话不多说,解释一下功能:查找一个字符串是否存在于另一个字符串  ↓

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s = "CSDN.net";
    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个字呢)) ……

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值