【问题标题】:Capitalize a single letter instead of the entire sentence大写单个字母而不是整个句子
【发布时间】:2020-09-30 22:37:15
【问题描述】:

如何大写例如字母“i”?我试过变换,转换。现在,我认为使用 for 循环可能是最好的选择,但似乎无法弄清楚!

#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "this is a test, this is also a test, this is yet another test";
int strLen = 0;
strLen = s.length();
for() //this is where I can't seem to figure it out
cout << s << endl;
return 0;
}

【问题讨论】:

  • 这是答案:s[0] = std::toupper(s[0]);。将0 替换为要大写字母的位置。
  • 给你:for(auto&amp; c : s) { c = c == 'i' ? (char)std::toupper(c) : c; }
  • @ThomasMatthews 谢谢。您的解决方案有效,但涉及多个条目。我很感激。
  • @πάνταῥεῖ 太棒了!非常感谢。
  • char 值上从std::string 调用std::toupper 通常是不安全的 - 您应该使用std::toupper(static_cast&lt;uint8_t&gt;(c))。请参阅 cppreference docs - 参数是 int 并且必须可以表示为 unsigned char。简单地说char - std::string 中的元素类型,可以根据您的实现有符号或无符号。 (这样做的原因是实现可以简单地索引到 256 个chars 的数组 - 其中小写字母被替换为大写字母,使用输入作为索引)

标签: c++ toupper


【解决方案1】:

这是std::的方式:

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;

int main()
{
  string s = "this is a test, this is also a test, this is yet another test";
  char ch = std::toupper('i');
  std::replace(s.begin(), s.end(), 'i', ch);
  cout << s << endl;
  return 0;
}

【讨论】:

    【解决方案2】:
    // Assume that all dependencies have been included
    void replaceAllLetters (string& s, char toReplace) {
        char new = std::toupper(toReplace);
        std::replace(s.begin, s.end, toReplace, new);
    }
    void replaceOneLetter (string& s, int index) {
      if (index < s.size()) s[index] = std::toupper(s[index]);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 1970-01-01
      • 2017-03-30
      • 2012-06-23
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      相关资源
      最近更新 更多