C++ 统计英文长句中以 'y' 结尾的单词数量

问题描述: 在 1 个包含空格和若干单词的英文长句 (最多 100 字符) 中,统计以 'y' 结尾的单调的个数。

输入: 输入 1 个长句。

输出: 输出单词的个数。

思路: 遍历句子中的每一个单词,判断是否以 'y' 结尾,如果是则计数器加 1。需要注意的是,单词的定义是以空格分隔的一段字符,可以用字符串流 istringstream 来方便地实现。

代码如下:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
    string sentence;
    getline(cin, sentence);

    int count = 0;
    istringstream iss(sentence);
    string word;
    while (iss >> word) {
        if (word.back() == 'y') {
            count++;
        }
    }

    cout << count << endl;
    return 0;
}

示例:

输入:

today is my 16th birthday

输出:

3
C++ 统计英文长句中以 'y' 结尾的单词数量

原文地址: https://www.cveoy.top/t/topic/nQSV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录