我正在C++中编写一个grep函数(作为一个自我分配的练习 - 我意识到它没有实际的grep特性的功能)采取原始字符串和您正在寻找的搜索字符串。在代码中,我输入了一个grep字符串中的所有字符,直到它看到的第一个空格。然后我将grep字符串中的字符与搜索字符串进行比较,如果匹配,则将其存储在一个临时字符串中。我遍历grep字符串并将搜索字符串的长度与临时字符串进行比较以查看它是否匹配。比较字符串大小是比较字符的可接受替代方法吗?
我的问题:那种形式不好,比较长度?我可以使用for循环来比较每个单独的字符,但似乎不太会吃掉CPU周期。这里是我的输入函数供参考:
std::string grep(std::string originalStr, std::string searchStr)
{
std::string grepStr = "";
std::string finalStr = "";
//stores final string; is the return value
finalStr.resize(originalStr.length() + 1);
grepStr.resize(originalStr.length() + 1);
int place = 0;
//remember where you are in originalStr[place]
int numOfOccurences = 0;
//remember number of times searchStr was found;
//not necessary
std::string tempStr = "";
//will temporarily hold grepStr
//handles case if first occurence is a space
if (originalStr[0] == ' ')
{
place++;
}
while (place != originalStr.length())
{
tempStr = "";
while (originalStr[place] != ' ')
{
if (originalStr[place] == ' ')
{
break;
}
grepStr[place] = originalStr[place];
++place;
}
++place;//ensures you skip over the space next pass
for (int i = 0; i != grepStr.length(); i++)
{
if (grepStr[i] == searchStr[i])
{
//if they are the same, append that char..
tempStr[i] = grepStr[i];
if (tempStr.length() == grepStr.length())
//..then check for string length; if same, searchStr equals tempStr
//and you can append grepStr to the finalStr
{
for (int x = 0; x != finalStr.length(); x++)
{
finalStr[x] = grepStr[x];
}
++numOfOccurences;
//add one to the number of occurences in originalStr
finalStr += ' ';
//add a space IF you find the string
}
}
}
}
return finalStr;
}
我发现链接关于Boyer-Moore快速字符串搜索算法非常有趣,谢谢! – 2009-05-18 01:13:42
很高兴喜欢它。它确实是一种很酷的算法;真的很违反直觉,你可以做很快的字符串匹配。 – 2009-05-18 02:44:47