我目前正试图将角色'i'大写,但仅限于它本身
这是我的代码
int main()
{
string textMessage = "Yesterday’s Doctor Who broadcast made me
laugh and cry in the same episode! i can only wonder what the
Doctor will get into next. My family and i are huge fans.";
replace(textMessage.begin(), textMessage.end(), 'i', 'I');
cout << textMessage;
}
我的输出是
Yesterday’s Doctor Who broadcast made me laugh and cry In the same epIsode! I can only wonder what the Doctor wIll get Into next. My famIly and I are huge fans.
这是我想要的输出
Yesterday’s Doctor Who broadcast made me laugh and cry in the same episode! I can only wonder what the Doctor will get into next. My family and I are huge fans.
答案 0 :(得分:0)
一封信本身就是一个被空白包围的字母,而不是其他字母。一个字母本身也很容易解释,因为它总是被空格包围。
replace(textMessage.begin(), textMessage.end(), ' i ', ' I ');
如果您将程序中的代码更改为此(它替换了具有大写字母I&#39; s的空格),它应该可以正常工作。
答案 1 :(得分:0)
您不必使用替换函数,而是必须遍历字符串并仅检查空格前面和后面的“i”,并将其替换为“I”。我想以下代码段可以实现您想要实现的目标: -
for (int iTraverse = 0; iTraverse< textMessage.length(); iTraverse++)
{
if (textMessage[iTraverse] == 'i' && textMessage[iTraverse-1] == ' ' && textMessage[iTraverse+1] == ' ')
{
textMessage[iTraverse] = 'I';
}
}