C 验证字符串2中是否存在字符串1

C++ Verify if string 1 exist in string 2

本文关键字:字符串 存在 是否 验证      更新时间:2023-10-16

请帮助我!

它不起作用,我没有犯错!

有一个函数可以验证彼此中的字符串存在吗?谢谢 !!

#include <iostream>
#include <string>
using namespace std;
int main()
{
string mot1="abc";
string mot2="oooooabcooo";
int j=1;
while((j!=mot1.length())||(j!=0))
{
    for(int i=0;i<=mot.length();i++)
    {
        if(mot1[i]==mot2[i])
            {j++;}
            else j=0;
    }
}
if(j==mot1.length())
    cout<<mot1<<" existe dans "<<mot2<<endl;
    else
            if(j=0)
        cout<<"erreur";
return 0;
}

这是您要寻找的功能。

mot2.find(mot1); // also std::find

希望这会有所帮助。

有一个盒子工具,但是如果您寻找劳动编码,我对您的代码一无所知。相反,我以这种方式找到:

#include <iostream>
#include <string>
using namespace std;
int find(string mot1,string mot2)
{
    bool found;
    for(int j=0;j<mot2.length()-mot1.length()+1;j++)
    {
        found=true;
        cout<<"comparing "<<mot1.c_str()<<" and "<<(mot2.c_str()+j)<<endl;
        for(int i=0;i<mot1.length();i++)
            if(mot1[i]!=mot2[i+j])
            {
                found=false;
                break;
            }
        if(found)
            return j;
    }
    return -1;
}
int main()
{
    string mot1="abc";
    string mot2="oooooabcooo";
    cout<<find(mot1,mot2)<<endl;
    return 0;
}