在C ++中以字符串递归获取substring的索引

时间:2015-03-11 18:09:38

标签: c++ string recursion substring

鉴于功能:

int getIndex(string mystring, string substring);

如何找到mystring开始的substring索引?我不想使用默认的find函数,我想自己创建(在C ++中)。如果存在该子字符串,则我的find方法返回true。

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

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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);
}

答案 2 :(得分: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代替intstd::string::npos替换-1。:)