我现在明白了。您想在'z'
任何地方匹配至少包含 3 个字符的字符串。
使用std::count
. 这个例子:
#include <algorithm> // std::count
#include <iostream> // std::cout
#include <iterator> // std::begin, std::end
#include <string> // std::string
// This is the function you care about.
// It returns `true` if the string has at least 3 'z's.
bool has_3_zs (const std::string& s)
{
return std::count(std::begin(s), std::end(s), 'z') >= 3;
}
// This is just a test case. Ignore the way I write my loop.
int main()
{
for (auto& s : {"Hello", "zWorzldz", "Another", "zStzzring"} )
{
if (has_3_zs(s))
{
std::cout << s << '\n';
}
}
}
印刷:
zWorzldz
zStzzring
编辑:
好的,我写了一个更像你的例子。我的循环的编写方式与您的大致相同(我认为这不是最好的,但我不想进一步混淆)。
// This is the function you care about.
// It returns `true` if the string has at least 3 'z's.
bool has_3_zs (const std::string& s)
{
return std::count(std::begin(s), std::end(s), 'z') >= 3;
}
struct SomeTypeWithAWord
{
std::string word; // The bit you care about
// Allow me to easily make these for my example
SomeTypeWithAWord(char const * c) : word(c) {}
};
// This will contain the words.
// Don't worry about how I fill it up,
// I've just written it the shortest way I know how.
std::vector<SomeTypeWithAWord> myWords
{"Hello", "zWorzldz", "Another", "zStzzring"};
// This is the function you are trying to write.
// It loops over `myWords` and prints any with 3 or more 'z's.
void findzs()
{
std::cout << "List : \n";
std::vector<SomeTypeWithAWord>::size_type wordIndex = 0;
while (wordIndex < myWords.size()) // Loop over all the words
{
const std::string& testWord = myWords[wordIndex].word;
if (has_3_zs(testWord)) // Test each individual word
{
std::cout << testWord << '\n'; // Print it
}
++wordIndex;
}
}
int main()
{
findzs();
}