在较大的字符串中搜索字符串

Searching for a String within a larger string

本文关键字:字符串 搜索      更新时间:2023-10-16

我真的需要程序的最后一部分的帮助。我需要在较大的字符串中找到一个字符串,如果找到,则返回子字符串的开始位置。从方向:

请注意,字符串位置从 0 开始,以长度 -1 结束。如果未找到该字符串,将返回值 -1。

已经开始并编译了以下代码,我只想知道这是否真的正确。我不想太过分,但我需要专家的一些反馈。我这样做对吗?或者至少我正朝着正确的方向前进?

const int MyString::Find(const MyString& other)
{
    int start(0);
    int counter(0);
    int end = other.Size;
    int count(0);
    int end1 = Size;
    int nfound = -1;
    char* temp;
    if(other.String[0] != '' && other.String[0] != ' ')
    {
        if(other.String[count] == String[counter])
        {
            start = counter;
            for(int i = count; i < end-1;i++)
            {
                for(int j = counter; j < end1 -1; j++)
                {
                    temp[j] = String[j];
                }
            }
            if(other == temp)
            {
                return start;
            }
            else
                return nfound;
        }
        else{
            while(other.String[count] != String[counter])
            {
                counter++;
                if(other.String[count] == String[counter])
                {
                    start = counter;
                    for(int i = count; i < end-1;i++)
                    {
                        for(int j = counter; j < end1 -1; j++)
                        {
                            temp[j] = String[j];
                        }
                    }
                    if(other == temp)
                    {
                        return start;
                    }
                    else
                        return nfound;
                }
            }
        }
    }
    else
    {
        return nfound;
    }
}

假设您不想做任何非常复杂的事情,请考虑needlehaystack的子字符串,当且仅当存在某个haystack索引,其从该索引开始的子字符串等于 needle 时。

此外,您不需要复制大量子字符串。从您选择的索引开始,只需逐个字符比较,直到 (a) 您发现不匹配,在这种情况下尝试另一个索引,或 (b) 您用完haystack,在这种情况下,这个或任何更大的索引都不可能匹配,否则 (c) 您用完needle,在这种情况下,您找到了匹配项, 因此,返回您正在使用的索引。

如果有多个匹配项(例如在"banana"中搜索"na"),那么希望方向会告诉您返回哪一个。这告诉您考虑 haystack 中的索引的顺序。

如果你确实想做一些非常复杂的事情,可以查找Boyer-Moore,Knuth-Morris-Pratt和许多其他已发布的字符串搜索算法,这些算法具有不同的权衡。似乎需要不止一个人才能发明一个好的。

从我的角度来看,这是一段糟糕的代码。\0 在字符*字符串中用于指示字符串的结尾。没有必要在封装字符串的类中使用它。有许多算法可以在字符串中查找子字符串,其中之一是 Knuth-Morris-Pratt 算法。本文中列出了其他字符串搜索算法