P5734 【深基6.例6】文字处理软件

文章目录

https://www.luogu.com.cn/problem/P5734

在这里插入图片描述
纯手写

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    int q,i;string str,t,s;
    cin >> q >> str;
    while(q--)
    {
        cin >> i;
        switch (i)
        {
        case 1:
            cin >> t;
            str = str + t;
            cout << str << endl;
            break;
        case 2:
            int l,len;
            cin >> l >> len;
            t = str;
            str = "";
            for(int j = l;(j <= l + len)&&(j < t.size());j++)//这里应该是<不是小于等于,因为要算上l自己
            {
                str += t[j];
            }
            cout << str << endl;
            break;
        case 3:
            int p;
            cin >> p >> t;
            s = str;
            str = "";
            for(int j = 0;j < p;j++)
                str += s[j];
            str += t;
            for(int j = p;j < s.size();j++)
                str += s[j];
            cout << str << endl;
            break;
        case 4:
            cin >> t;
            if(str.find(t) <= str.size())
                cout << str.find(t) << endl;
            else 
                cout << -1 << endl;
            break;

        default:
            break;
        
        }
    }
}
  • 不知道为什么会在两个点上WA,最后发现是for(int j = l;(j <= l + len)&&(j < t.size());j++)//这里应该是<不是小于等于,因为要算上l自己 xixin
  • 使用括号运算符代替&&, for(int i=b;i<(e.length(),b+c);i++)
  • STL自带库函数find的应用,因为find有时会返回奇奇怪怪的数,所以要特判,但是一定不会大于字符串长度
  • 在分割字符串时,使用空字符串迂回构造
  • a.length()和a.size()没有区别

大佬

STL函数

substr 生成子串,输入位置和长度

insert 在字符串中插入字符串

find 查找字符串中某个字符串的位置并返回它的位置

str函数可以看到具体用法

if(a==1)//操作1
        {
            cin>>b1;
            qwq+=b1;
            cout<<qwq<<endl;
        }
        else if(a==2)//操作2
        {
            cin>>b>>c;
            c1=qwq.substr(b,c);
            qwq=c1;
            cout<<qwq;
            cout<<endl;
        }
        else if(a==3)//操作3
        {
            cin>>b>>b1;
            qwq.insert(b,b1);
            cout<<qwq<<endl;
        }
        else if(a==4)//操作4
        {
            cin>>b1;
            if(qwq.find(b1)<qwq.size())//找不到会返回一个诡异的数字(反正比字符串长)
            cout<<qwq.find(b1)<<endl;
            else
            cout<<-1<<endl;
        }
    }
发布了372 篇原创文章 · 获赞 48 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/dghcs18/article/details/104291453
今日推荐