我应该如何在 c++ 中查找两个字符中的字符串

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

本文关键字:两个 字符 字符串 c++ 查找 我应该      更新时间:2023-10-16

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

sdfgkjr$joeisawesome$sdfeids -> joeisawesome

编辑:另一个答案是寻找字符串中是否存在字符串。我正在寻找两个字符中的字符串,并在两个字符中输出刺痛。感谢您查看 PoX。

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

例:

#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
}