substr函数|字符串截取

E. 学妹的任务 [ 问题 5097 ] [ 讨论 ]
Description
阿梓学妹给你n个字符串,请按照输入顺序拼接字符串。拼接指的是如果两个字符串首尾具有最长的相同的部分就连接在一起。例如:假设"baccano"是当前已经拼接出来的字符串,"canot"是下一个串,

𝑏𝑎𝑐𝑐𝑎𝑛𝑜 𝑐𝑎𝑛𝑜𝑡 → 𝑏𝑎𝑐𝑐𝑎𝑛𝑜𝑡

其中加黑部分代表最长的相同的首尾部分。

Input
第一行包含一个整数n ,代表字符串个数

接下来n 行每行一个字符串

n小于等于100,每个字符串长度小于等于100

Output
一行一个字符串代表最终答案

Samples
Input 复制
3
baccano
canot
tt
Output
baccanott
Input 复制
3
a
b
c
Output
abc

#include<bits/stdc++.h>
using namespace std;
#define PI 3.1415926535897932384
#define repb(a,b,i) for(int i=a;i<=b;i++)
#define repk(a,b,i) for(int i=a;i<b;i++)
#define unrepb(a,b,i) for(int i=a;i>=b;i--)
#define unrepk(a,b,i) for(int i=a;i>b;i--)
typedef long long ll;
const int UNINF=-0x3f3f3f3f;
const int INF=0x3f3f3f3f;
const int maxn=2e3+7;
const int mod=1000;
inline ll read()
{
    ll zf=1,x=0;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-')
            zf=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x=(x<<3)+(x<<1)+(ch^48);
        ch=getchar();
    }
    return zf*x;
}
priority_queue<int,vector<int>,greater<int> >v;
#define read read()
//#define size size()
string s[maxn];
int main()
{
    int n=read;
    repb(1,n,i) cin>>s[i];
    string st=s[1];
    for(int i=2;i<=n;i++){
        int flag=0;
        int len=s[i].size();
        int lenst=st.size();
        for(int j=len;j>=0;j--){
           // if(lenst>=j)
           // cout<<st.substr(lenst-j,lenst)<<" "<<s[i].substr(0,j)<<endl;
            if(lenst>=j)
            if(st.substr(lenst-j,lenst)==s[i].substr(0,j)){
                string temp=s[i].substr(j,len);
                st+=temp;
                flag=1;
                break;
            }
        }
        if(!flag) st+=s[i];
    }
    cout<<st;
    return 0;
}

这个substr 简单地记就是前闭后开 substr(start,end);

string str;
    cin>>str;
    int len=str.size();
    cout<<"len="<<len<<endl;
    for(int i=0;i<=len;i++){
        cout<<str.substr(i,len)<<" "<<i<<endl;
    }
    return 0;


当substr(len,len)的时候返回空
下标从0开始

string str;
    cin>>str;
    int len=str.size();
    cout<<"len="<<len<<endl;
    for(int i=0;i<len;i++){
        cout<<str.substr(i,len)<<" "<<i<<endl;
    }
    return 0;

在这里插入图片描述
substr参数必须大于等于0 小于0不对!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值