C++实现单词首字母大写,其余小写
以下是使用C++编写的程序,实现输入的每个单词的首字母大写,后续字母小写,非字母保持不变的转换,并最终输出结果:
#include <iostream>
#include <cctype>
std::string capitalizeWord(const std::string& word) {
std::string capitalizedWord = word;
if (!capitalizedWord.empty()) {
capitalizedWord[0] = std::toupper(capitalizedWord[0]);
for (size_t i = 1; i < capitalizedWord.length(); i++) {
capitalizedWord[i] = std::tolower(capitalizedWord[i]);
}
}
return capitalizedWord;
}
std::string processSentence(const std::string& sentence) {
std::string processedSentence;
std::string word;
for (char ch : sentence) {
if (std::isalpha(ch)) {
word += ch;
} else {
if (!word.empty()) {
processedSentence += capitalizeWord(word) + ch;
word.clear();
} else {
processedSentence += ch;
}
}
}
if (!word.empty()) {
processedSentence += capitalizeWord(word);
}
return processedSentence;
}
int main() {
std::string sentence;
while (true) {
char ch = getchar();
if (ch == '.') {
break;
}
sentence += ch;
}
std::string processedSentence = processSentence(sentence);
std::cout << processedSentence << std::endl;
return 0;
}
注意:上述代码是用C++编写的,实现了输入的每个单词的首字母大写,后续字母小写,非字母保持不变的转换,并最终输出结果。您可以将输入以字符的形式逐个获取并进行处理,最后输出转换后的句子。
原文地址: https://www.cveoy.top/t/topic/VS7 著作权归作者所有。请勿转载和采集!