我编写了一个小方法来查看一个字符串是否包含另一个字符串。我只是有一个小问题,虽然,它总是返回假。
给定的干草堆是一个名为salaryCheck的字符串,值为"10.1",而指针是“”。它总是返回假的。
根据我的理解,它应该返回true,我首先将所有内容放入字符向量中,以提高可读性。然后输入一个循环,检查第一个指针字符是否与haystacki匹配。如果第一个指针字符与haystacki匹配,则继续进入另一个循环,将从haystacki开始的所有干草堆与针字符的完整列表进行比较。
据我所知,在我给出的论点中,这应该是正确的。
这是我的密码:
bool contains(std::string& haystack, std::string needle){
if (haystack.size() < needle.size())
return false;
bool returnValue = false;
std::vector<char> haystackChars;
std::vector<char> needleChars;
for (char c : haystack)
haystackChars.push_back(c);
for (char c : needle)
needleChars.push_back(c);
for (int i = 0; i < haystackChars.size() && !returnValue; i++){
if (needleChars[0] == haystackChars[i])
for (int i2 = i; i2 < needleChars.size(); i2++){
if (needleChars[i2] == haystackChars[i2])
returnValue = true;
else{
returnValue = false;
break;
}
}
}
return returnValue;
}发布于 2014-09-18 16:00:05
问题就在这里
for (int i2 = i; i2 < needleChars.size(); i2++){您应该在0和needleChars.size()之间循环,或者在i和i + needleChars.size()之间循环。下面的if语句也需要调整;needle和haystack的正确数组索引将不一样。
发布于 2014-09-18 16:15:53
几分钱,随你便。
bool contains(std::string& haystack, std::string needle){
// you only need to inspect haystack and needle, so
bool contains(const std::string& haystack, const std::string& needle)
// is preferred. You also get convinient constructors, simplifying the
// function call. And of course the const guarantee
// This is ok.
if (haystack.size() < needle.size())
return false;
// returnValue will be unneccesary, you can leave as soon as you find the positive.
bool returnValue = false;
// The vector does not add anything useful. std::string works fine with indexes.
std::vector<char> haystackChars;
std::vector<char> needleChars;
for (char c : haystack)
haystackChars.push_back(c);
for (char c : needle)
needleChars.push_back(c);
// The algorithm is unnecessarily complex,
// use the string members to simplify.
for (int i = 0; i < haystackChars.size() && !returnValue; i++){
if (needleChars[0] == haystackChars[i])
// This for statment can be rewritten as
if ( haystack.substring( i, needleSize ) == needle )
return true;
for (int i2 = i; i2 < needleChars.size(); i2++){
if (needleChars[i2] == haystackChars[i2])
returnValue = true;
else{
returnValue = false;
break;
}
}
}
// this becomes return false.
return returnValue;
}因此,通过这些修订:
bool contains(const std::string& haystack, const std::string& needle){
if (haystack.size() < needle.size())
return false;
size_t needleSize = needle.size();
for (int i = 0; i < haystack.size(); i++){
if ( haystack.substr( i, needleSize ) == needle )
return true;
}
return false;
}正如dyp所指出的,substr可能是潜在的代价高昂的字符串::find来拯救。条件也可以写为
if ( haystack.find( needle.c_str(), i, needleSize ) == i )
return true;当然,如果这不是一次演习,这将是
if ( haystack.find( needle ) != string::npos )https://stackoverflow.com/questions/25917244
复制相似问题