substr复制子字符串:

先讲一下substr的用法:字符串.substr(a,b)

前面一定要加上是哪个字符串。

a指的是从第几个字符开始,当然字符串是从零开始数的。
b指的是从第a开始到后面数几个结束,即b代表的数量。

百度含义:substr是C++语言函数,主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。如果没有指定长度_Count或_Count+_Off超出了源字符串的长度,则子字符串将延续到源字符串的结尾。

原先做这道题用的是队列,不过也是过了,但就是有些麻烦(大体讲一下思路,就是用一个for循环,从第一个字符串的第一个字母开始找,如果跟第二个字符串相应的字符相等,就push进队列,并标记,如果遇到不相等,则将队列pop。。。中间还有很多细节,就不说了,很繁琐,不建议尝试,还是好好学习substr吧)。

下面请瞻仰大佬的代码,简直是又对又短。

#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>

using namespace std;
int main ()
{
    string a,b;
    while (cin >> a >> b)
    {
        int len1=a.length();
        int len2=b.length();
        int len=min(len1,len2);
        for(int i=len;i>=1;i--)
        {
            if(a.substr(len1-i,i)==b.substr(0,i))
            {
                cout << b.substr(0,i) << endl;
                break;
            }
            else if(i==1)
            {
                cout << "\"NULL!\"" << endl;
            }
        }
    }
    return 0;
}