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