首页 > 解决方案 > 对向量字符串中的第一个字符使用 toupper

问题描述

如何使用toupper()将字符串向量中每个元素的第一个字母转换为大写?

这是我尝试过的...

string word;
vector<string> text;
while(cin >> word){
    text.push_back(word);
}

for(decltype(text.size()) i = 0; i != text.size()) {
    text[0] = toupper(text);
}

标签: c++

解决方案


for(auto& s : text)
    if (!s.empty()) s[0] = std::toupper(s[0]);

或者更花哨:

std::transform(std::istream_iterator<std::string>{std::cin}, {},
              std::back_inserter(text),
              [](auto s) {
                  if (!s.empty()) s[0] = std::toupper(s[0]);
                  return s;
              });

推荐阅读