2017-04-05 82 views
-4
替换字符

林目前正在尝试利用字符“我”,但只有当它本身C++字符串中

这是代码我有

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.

+2

拿出一张纸,并决定写下来,在简短的句子,逻辑进程是否字母'i'在字符串本身,或者是一个词的一部分。这应该不会超过一分钟左右。 ...好的,时间到了!现在简单地把你写下来的东西直接翻译成代码。问题解决了。 –

回答

0

而不是使用替换函数,你将不得不遍历整个字符串,并检查只有那些'我',前面和后面有一个空格,并将它们替换为'我'。我想下面的代码段会做你想要达到的: -

for (int iTraverse = 0; iTraverse< textMessage.length(); iTraverse++) 
{ 
    if (textMessage[iTraverse] == 'i' && textMessage[iTraverse-1] == ' ' && textMessage[iTraverse+1]  == ' ') 
    { 
     textMessage[iTraverse] = 'I'; 
    } 
} 
+0

谢谢那正是我需要 –

+0

提到它不是,但你应该做到这一点,而不是依靠别人,因为它不是很难实现:) – Valgrind1691

+0

我绝对明白你是从哪里来的,我宁愿自己弄清楚,但我的事情是我没有找到确切的答案,我只需要知道我可以计算出所有其他东西的函数 –

0

字母本身是一个字母,它被空白包围,而不是其他字母。一封信本身也很容易解释,因为它总是被空白包围。

replace(textMessage.begin(), textMessage.end(), ' i ', ' I '); 

如果你在程序这一更改代码(它取代我的是有大写我的空白),它应该工作。

+0

我试过了,没有sucees –

+0

你的输出是什么? –

+0

所有'我'呆在小写 –