2012-11-19 157 views
-1

我需要创建一个接受两个字符和一个字符串并返回一个字符串的函数。
函数应该将第一个参数中的所有字母替换为第二个参数
参数。 例如,如果传递的字符串是“How now cow”,并且函数将全部'o'替换为'e',那么新字符串将是:“Hew new cew”。创建函数来替换字符串中的某些字母?

我知道这是错误的,但我怎么能修改此代码的工作?

#include <iostream> 
using namespace std; 

string replace(char a, char b, string Rstring){ 
string Restring; 

Restring= Rstring.replace('o', 2, 'e') 

return Restring; 
} 

int countspace(string mystring){ 
int counter; 
for (int i=0;i<mystring.length();i++){ 

if (mystring[i]== ' ') 
counter++; 
} 
return counter; 


} 
+0

替换函数,但对我来说有点困难,因为接受的字符串是用户生成的。 –

+0

抱歉,我是新手 –

+0

发布您写的代码无法正常工作。事实上,你基本上是要求某人为你做。 – Yuushi

回答

1

std::string.replace不会做你想要的。相反,你应该写自己的方法,这样做并不难。

replaceChars(string *str, char old, char replacement) 
{ 
     for(char& c : str) { 
     if (c == old) 
      c = replacement; 
     } 
} 

该循环只能在C++ 11中工作,所以如果它不起作用使用这个insead;

 while(char* it = str; *it; ++it) { 
      if (*it == old) // dereference the pointer, we want the char not the address 
      *it = replacement; 
     } 

您将此指针传递给字符串和要交换的字符。当你遇到你设置替换的旧字符时,它通过char循环字符串char。 for循环使用对c的引用,因此您将更改字符串,无需分配新字符串或任何内容。如果您没有使用std::string,则可以使用字符数组轻松完成此操作。这个概念完全一样。

+0

感谢帮助! –

相关问题