在C ++中递归获取字符串中子字符串开始的索引

Recursively get index of substring start in string in C++

给定函数:

int getIndex(string mystring, string substring);

如何找到 mystring 的索引,其中 substring 开始,如果有的话?我不想使用默认的 find 函数,我想创建自己的函数(在 C++ 中)。如果存在该子字符串,我的查找方法 return 为真。

到目前为止我有以下想法:

int getIndex(string mystring, string substring)
{
    if(find(mystring, substring))
        return counter();
return -1;
}
int counter()
{
        int count; //I'm not sure how to use this value without a global
                     //variable or variable declared in main()
        ++count;
}

如何迭代字符串,每次字符与子字符串的第一个字符匹配时停止,然后查看计数器是否足够小以适合子字符串,如果是,则在子循环字符中迭代要找到匹配的字符?

创建一个重载函数来完成实际工作并使其递归。使用起始索引从第一个函数调用第二个函数。

int getIndex(char const* mystring, size_t len1,
             char const* substring, size_t len2, int index)
{
   if ( len1 < len2 )
   {
      return -1;
   }

   if ( strncmp(mystring, substring, len2) == 0)
   {
     return index;
   }

   return getIndex(mystring+1, len1-1, substring, len2, index+1);   
}

int getIndex(string mystring, string substring)
{
   return getIndex(mystring.c_str(), mystring.size(),
                   substring.c_str(), substring.size(),
                   0);
}

函数可以这样写

std::string::size_type GetIndex( const std::string &myString, 
                                 const std::string &subString )
{
    if ( myString.size() < subString.size() ) return std::string::npos;
    if ( myString.substr( 0, subString.size() ) == subString ) return 0;

    std::string::size_type n = GetIndex( myString.substr( 1 ), subString );

    return ( n == std::string::npos ) ? std::string::npos : n + 1;
}                                 

这是一个演示程序

#include <iostream>
#include <string>

std::string::size_type GetIndex( const std::string &myString, 
                                 const std::string &subString )
{
    if ( myString.size() < subString.size() ) return std::string::npos;
    if ( myString.substr( 0, subString.size() ) == subString ) return 0;

    std::string::size_type n = GetIndex( myString.substr( 1 ), subString );

    return ( n == std::string::npos ) ? std::string::npos : n + 1;
}                                 

int main()
{
    std::string::size_type n = GetIndex( "Hello World", "World" );

    if ( n != std::string::npos )
    {
        std::cout << "The substring is found at position " << n  << std::endl;
    }
    else
    {
        std::cout << "The substring is not found" << std::endl;
    }

    n = GetIndex( "Hello C", "C++" );

    if ( n != std::string::npos )
    {
        std::cout << "The substring is found at position " << n  << std::endl;
    }
    else
    {
        std::cout << "The substring is not found" << std::endl;
    }
}    

它的输出是

The substring is found at position 6
The substring is not found

如果您愿意,可以用 std::string::size_type 代替 int,用 std::string::npos 代替 -1。:)