c++编写一个函数,接受一个字符串,将其中的每个单词的首字母转换为大写,其他字母转换为小写。
作者:野牛程序员:2023-08-11 20:25:04 C++阅读 2898
c++编写一个函数,接受一个字符串,将其中的每个单词的首字母转换为大写,其他字母转换为小写。
#include <iostream>
#include <string>
#include <cctype>
std::string titleCase(const std::string& input) {
std::string result = input;
bool newWord = true;
for (size_t i = 0; i < result.length(); ++i) {
if (std::isalpha(result[i])) {
if (newWord) {
result[i] = std::toupper(result[i]);
newWord = false;
} else {
result[i] = std::tolower(result[i]);
}
} else {
newWord = true;
}
}
return result;
}
int main() {
std::string text = "thIs is a tEsT SenTEnce.";
std::string title = titleCase(text);
std::cout << "Title case: " << title << std::endl;
return 0;
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

