MST

星途 面试题库

面试题:C++字符常量与字符串常量在复杂条件下的比较

假设给定一个字符串常量str,其内容为一段英文句子。再给定一个字符常量ch。请编写一个函数,该函数能够统计字符串常量str中,以字符常量ch开头的单词数量,并返回这个数量。要求考虑单词边界,例如标点符号等。
37.9万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
def count_words_starting_with(str, ch):
    words = str.split()
    count = 0
    for word in words:
        word = word.strip('.,:;?!\'\"')
        if word.startswith(ch):
            count += 1
    return count

你可以这样调用这个函数:

str = "Hello, world! How are you? Happy holidays."
ch = 'H'
result = count_words_starting_with(str, ch)
print(result)

在C++ 中:

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

int countWordsStartingWith(const std::string& str, char ch) {
    std::istringstream iss(str);
    std::string word;
    int count = 0;
    while (iss >> word) {
        // 去除单词两端的标点符号
        while (!word.empty() && std::ispunct(word.back())) {
            word.pop_back();
        }
        while (!word.empty() && std::ispunct(word.front())) {
            word.erase(0, 1);
        }
        if (!word.empty() && word[0] == ch) {
            count++;
        }
    }
    return count;
}

你可以这样调用这个函数:

int main() {
    std::string str = "Hello, world! How are you? Happy holidays.";
    char ch = 'H';
    int result = countWordsStartingWith(str, ch);
    std::cout << result << std::endl;
    return 0;
}

在Java中:

public class CountWordsStartingWith {
    public static int countWordsStartingWith(String str, char ch) {
        String[] words = str.split("\\s+");
        int count = 0;
        for (String word : words) {
            word = word.replaceAll("^[\\p{Punct}]+|[\\p{Punct}]+$", "");
            if (!word.isEmpty() && word.charAt(0) == ch) {
                count++;
            }
        }
        return count;
    }
}

你可以这样调用这个函数:

public class Main {
    public static void main(String[] args) {
        String str = "Hello, world! How are you? Happy holidays.";
        char ch = 'H';
        int result = CountWordsStartingWith.countWordsStartingWith(str, ch);
        System.out.println(result);
    }
}