面试题答案
一键面试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);
}
}