在较大的字符串中搜索字符串
Searching for a String within a larger string
我真的需要程序的最后一部分的帮助。我需要在较大的字符串中找到一个字符串,如果找到,则返回子字符串的开始位置。从方向:
我请注意,字符串位置从 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;
}
}
假设您不想做任何非常复杂的事情,请考虑needle
是haystack
的子字符串,当且仅当存在某个haystack
索引,其从该索引开始的子字符串等于 needle
时。
此外,您不需要复制大量子字符串。从您选择的索引开始,只需逐个字符比较,直到 (a) 您发现不匹配,在这种情况下尝试另一个索引,或 (b) 您用完haystack
,在这种情况下,这个或任何更大的索引都不可能匹配,否则 (c) 您用完needle
,在这种情况下,您找到了匹配项, 因此,返回您正在使用的索引。
如果有多个匹配项(例如在"banana"
中搜索"na"
),那么希望方向会告诉您返回哪一个。这告诉您考虑 haystack
中的索引的顺序。
如果你确实想做一些非常复杂的事情,可以查找Boyer-Moore,Knuth-Morris-Pratt和许多其他已发布的字符串搜索算法,这些算法具有不同的权衡。似乎需要不止一个人才能发明一个好的。
从我的角度来看,这是一段糟糕的代码。\0 在字符*字符串中用于指示字符串的结尾。没有必要在封装字符串的类中使用它。有许多算法可以在字符串中查找子字符串,其中之一是 Knuth-Morris-Pratt 算法。本文中列出了其他字符串搜索算法
- 哪个更快:在 1d 向量中按字符串搜索还是在 2d 向量中按向量搜索?
- 有序地图字符串搜索与整数搜索之间的时间复杂度
- 使用图形的字符串搜索算法?C++
- C++子字符串搜索 - 跳入C++
- 字符串搜索 - 并行版本较慢
- 使用Robert Sedwick书中的符号表进行字符串搜索
- C++中的部分字符串搜索
- 哪个是更好的字符串搜索算法?Boyer-Moore或Boyer Moore Horspool
- 如何使用 c++ 将字符串搜索到字符串数组中
- 使用 C++ 在文件中进行字符串搜索/索引
- Qt5 中字符串搜索的最佳容器
- 优化.txt文件中的字符串搜索
- 字符串搜索输入中包含的单词
- Boyer-Moore-坏字符规则实现子字符串搜索
- 带星号*通配符的字符串搜索
- c++字符串搜索函数
- 最好的字符串搜索算法
- 通配符字符串搜索算法
- 在c++中使用字符串(搜索字符串,分割字符串,cout<<字符串)
- Strstr()函数重叠字符串搜索