C++ 统计以 'y' 结尾的单词个数 (英文长句)

问题描述:

给定一个包含空格和多个单词的英文长句(最多 100 个字符),统计以字母 'y' 结尾的单词个数。

输入:

输入一个英文长句。

输出:

输出以 'y' 结尾的单词个数。

示例:

输入:

'today is my 16th birthday'

输出:

1

代码实现:

#include <iostream>
#include <string>

using namespace std;

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

    int count = 0;
    int start = 0;
    for (int i = 0; i < sentence.length(); i++) {
        if (sentence[i] == ' ' || i == sentence.length() - 1) {
            if (i == sentence.length() - 1) {
                i++;
            }
            string word = sentence.substr(start, i - start);
            if (word[word.length() - 1] == 'y') {
                count++;
            }
            start = i + 1;
        }
    }

    cout << count << endl;

    return 0;
}

代码解释:

  1. 使用 getline 函数读取用户输入的英文长句。
  2. 使用 for 循环遍历长句的每个字符。
  3. 当遇到空格或到达长句末尾时,提取当前单词。
  4. 判断提取的单词的最后一个字符是否为 'y',如果是,则计数器加 1。
  5. 打印计数器,即以 'y' 结尾的单词个数。
C++ 统计以 'y' 结尾的单词个数 (英文长句)

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

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