我写了一个小方法来查看字符串是否包含另一个字符串。 我只有一个小问题,它总是返回false。
鉴于haystack是一个名为salaryCheck的字符串,其值为" 10.1",并且针是"。"。它总是返回false。
根据我的理解,它应该返回true,我首先将所有内容放入字符向量中以便于阅读。然后我进入一个循环,在其中我检查第一个针符号是否与haystack [i]匹配。 如果第一个针头符号与haystack [i]匹配,我继续进入另一个循环,我将从haystack [i]开始的所有草堆与针头符号的完整列表进行比较。
据我所知,这应该与我给出的论点一致。
这是我的代码:
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;
}
答案 0 :(得分:1)
问题出在这里
for (int i2 = i; i2 < needleChars.size(); i2++){
您应该在0
和needleChars.size()
之间循环,或者i
和i + needleChars.size()
。以下if
声明也需要调整; needle
和haystack
的正确数组索引不会相同。
答案 1 :(得分:1)
几分钱,随你随心所欲。
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可能很昂贵,string ::找到救援。条件也可以写为
if ( haystack.find( needle.c_str(), i, needleSize ) == i )
return true;
当然,正如所建议的,如果这不是一个练习,那么这将是
if ( haystack.find( needle ) != string::npos )