C++ 将单个字母大写,而不是整个句子

C++ 将单个字母大写,而不是整个句子,c++,toupper,C++,Toupper,如何使用大写字母“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.l

如何使用大写字母“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;
}
#包括
#包括
使用名称空间std;
int main()
{
string s=“这是一个测试,这也是一个测试,这是另一个测试”;
int strLen=0;
strLen=s.长度();
for()//这就是我似乎无法理解的地方

cout这里有一个
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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
string s=“这是一个测试,这也是一个测试,这是另一个测试”;
char ch=std::toupper('i');
std::replace(s.begin(),s.end(),'i',ch);

cout这里有一个
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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
string s=“这是一个测试,这也是一个测试,这是另一个测试”;
char ch=std::toupper('i');
std::replace(s.begin(),s.end(),'i',ch);
cout
//假设已包含所有依赖项
void replaceAllLetters(字符串和字符替换){
char new=std::toupper(toReplace);
标准::更换(s.begin、s.end、toReplace、new);
}
void replaceOneLetter(字符串&s,整数索引){
如果(索引
//假设已包含所有依赖项
void replaceAllLetters(字符串和字符替换){
char new=std::toupper(toReplace);
标准::更换(s.begin、s.end、toReplace、new);
}
void replaceOneLetter(字符串&s,整数索引){
如果(索引
答案是:
s[0]=std::toupper(s[0]);
用你想大写的字母的位置替换
0
。给你:
for(auto&c:s){c=c='i'?(char)std::toupper(c):c;}
@ThomasMatthews谢谢。你的解决方案很有效,但涉及多个条目。我很感激。@πῥεῖ 太棒了!非常感谢。从
std::string
,在
char
值上调用
std::toupper
通常是不安全的-您应该使用
std::toupper(static_cast(c))
。请参见-参数是一个
int
,必须表示为
无符号字符
。简单地说就是
char
std::string
中的元素类型可能是有符号的,也可能是无符号的,具体取决于您的实现。(这样做的原因是,实现可以简单地索引到256个
char
s的数组中,其中使用输入作为索引,用大写字母替换小写字母)下面是答案:
s[0]=std::toupper(s[0]);
。将
0
替换为您要大写的字母位置。给您:
for(auto&c:s){c=c='i'?(char)std::toupper(c):c;}
@ThomasMatthews谢谢。您的解决方案很有效,但包含多个条目。我很感激。@πάνταῥεῖ 太棒了!非常感谢。从
std::string
,在
char
值上调用
std::toupper
通常是不安全的-您应该使用
std::toupper(static_cast(c))
。请参见-参数是一个
int
,必须表示为
无符号字符
。简单地说就是
char
std::string
中的元素类型可能是有符号的,也可能是无符号的,具体取决于您的实现。(这样做的原因是,实现可以简单地索引到一个256
char
s的数组中,其中小写的替换为大写的,使用输入作为索引)