c++ - C ++计算字符串中以'y'或'z'结尾的单词数
问题描述
我正在尝试编写一个程序,该程序查看单个字符串中每个单词的最后一个字母,并确定它是以 y 还是 z 结尾并对其进行计数。
例如:
“非斯日”-> 2
“一天 fyyyz”-> 2
我查找的所有东西都使用看起来像数组的东西,但我还不知道如何使用它们。我试图弄清楚如何使用 for 循环来做到这一点。
老实说,我不知道从哪里开始。我觉得我的一些较小的程序可以用来帮助解决这个问题,但我正在努力弄清楚如何将它们结合起来。
此代码计算字符串中的单词数量:
int words = 0;
bool connectedLetter;
for (auto c : s)
{
if (c == ' ')
{
connectedLetter = false;
}
if ( c != ' ' && connectedLetter == false)
{
++words;
connectedLetter = true;
}
尝试弄清楚如何让代码看到单独的单词可能会很有用。
我用这个程序来计算整个程序中元音的数量:
int vowels{0};
for (auto c : s)
{
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
|| c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
{
++vowels;
}
}
然后我做了一个小程序来查看字符串中的所有其他字母
auto len = s.size();
for (auto i = 0; i < len; i = i + 2)
{
result += s.at(i);
}
我觉得我知道它背后的概念,但是将它配置在一起阻止了我
解决方案
您还可以使用现有的 C++ 函数,这些函数专用于执行您想要的操作。
解决方案是利用基本的 IOstream 功能。您可能知道提取器运算符>>
将从流(如std::cin
或任何其他流)中提取单词,直到它遇到下一个空格。
所以读单词很简单:
std::string word{}; std::cin >> word;
将从中读取一个完整的单词std::cin
。
好的,我们有一个std::string
并且没有流。但这里 C++ 可以帮助您处理std::istringstream
. 这会将 a 转换std::string
为流对象。然后,您可以通过 this 使用所有 iostream 功能stringstream
。
然后,为了计算元素,按照特殊要求,我们有一个来自 C++ 库的标准算法:std::count_if
.
它需要一个开始和结束迭代器。在这里,我们简单地使用which 将为流中的所有字符串std::istream_iterator
调用提取器运算符。>>
使用 Lambda,std::count_if
我们检查一个单词是否满足要求的条件。
然后我们将得到一段非常紧凑的代码。
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <iterator>
int main() {
// test string
std::string testString{ "day fyyyz" };
// We want to extract words from the string, so, convert string to stream.
std::istringstream iss{ testString };
// count words, meeting a special condition
std::cout << std::count_if(std::istream_iterator<std::string>(iss), {},
[](const std::string& s) { return s.back() == 'y' || s.back() == 'z'; });
return 0;
}
当然,还有很多其他可能的解决方案。
编辑
Pete Becker 要求提供更灵活的解决方案。这里 C++ 也提供了一个专门的功能。std:: sregex_token_iterator 。
在这里,我们可以使用正则表达式指定任何单词模式,然后简单地获取或计算匹配项。
结果是一段更简单的代码:
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <regex>
const std::regex re{ R"(\w+[zy])" };
int main() {
// test string
std::string s{ "day, fyyyz, abc , zzz" };
// count words, meeting a special condition
std::cout << std::vector(std::sregex_token_iterator(s.begin(), s.end(), re), {}).size();
return 0;
}
推荐阅读
- ng-lightning - dropdown.child 中的下拉菜单触发父级并关闭
- javascript - Arrays.filter 未被识别为函数
- angular-console - 如何更改 @schemics/angular 用于生成组件的路径
- javascript - 使用Javascript将文本发送到新窗口的文本字段
- sonarqube - sonarQube 执行失败,“SonarQube 扫描仪执行期间出错”
- java - 如何使用 String.format 转义点字符
- javascript - 如何对数组进行分组并制作表格以在图表中显示?
- r - 将函数应用于所有列,其中一列使用 map 重复使用
- c# - 在 ASP.NET Core API 中上传到 WWWRoot 文件夹需要什么权限
- android - 如何在布局编辑器预览中更改内容字体大小?