我应该如何在 C++ 中的两个字符中找到一个字符串?

How should I go about finding a string within two chars in c++?

您好,我一直在尝试找到一种在两个字符中查找字符串的方法。我应该如何在 C++ 中执行此操作?

sdfgkjr$joeisawesome$sdfeids -> joeisawesome

编辑:另一个答案是寻找字符串中是否存在字符串。我正在寻找两个字符内的字符串并输出两个字符内的字符串。感谢您关注 PoX。

好的,所以当您说两个字符时,我假设您指的是定界符。在这种情况下,您将不得不使用 String.find() 来查找分隔符的位置。找到分隔符的位置后,您可以使用 String.substr(index1,index2-index1) 到 return 子字符串。

示例:

#include <iostream>
#include <string>

int main()
{
    std::size_t index1,index2;
    std::string myString = "sdfgkjr$joeisawesome$sdfeids";
    std::string sub= "";
    index1 = myString.find('$');

    //string::npos is -1 if you are unaware

    if(index1!=std::string::npos&& index1<myString.length()-1)
        index2=myString.find('$',index1+1);
    if(index2!=std::string::npos)
    {
        sub = myString.substr(index1+1,index2-index1);
    }   
    std::cout<<sub; //outputs joeisawesome
}