用一组字符替换所有字符

时间:2015-09-28 23:56:38

标签: c++ regex string char

我正在尝试用另一组字符替换字符串中的每个字符

for example a -> ABC
            b -> BCA
            d -> CBA

但我似乎遇到了这个看似简单的任务的问题

到目前为止我已经

#include <isotream>
#include "Class.h"
#include <string>
using namespace std;
  int main(){
      string test;
      cin >> test;
      Class class;
      cout << class.returnString(test);
}

在我的课程中,我打电话给我

#include "Class.h" //which has <string> <iostream> and std
static string phrase;
static string whole;
static int place;
Class::Class(){
if (phrase != ""){
    phrase = "";
}
if (whole != ""){
    whole = "";
}
if (place == NULL){
    place = 0;
}
}

void Class::reader(string x){
    char symbol = x.at(place);
    while (symbol != '\0'){
       place++;
       replacer(symbol);
       reader(x);
   }
}
void Class::replacer(char x){
    if (char x = 'a'){
        phrase = "hola";
    }
    if (char x = 'b'){
        phrase = "hi";
    }
    knitter();
 }
void Class::knitter(){
    whole = whole + phrase;
}

string Class::returnString(string x){
    reader(x);
    return whole;
}

当我尝试使用&#34; a&#34;运行它时,我一直收到一个无效的字符串位置作为错误在测试字符串中。

1 个答案:

答案 0 :(得分:1)

在while循环中,'symbol'始终为'a'。

void Class::reader(string x){
    char symbol = x.at(place);
    while (symbol != '\0'){
       place++;
       replacer(symbol);
       reader(x);
   }
}

你需要在while循环中读取'x',否则你的while循环永远不会终止。在无限程序中调用编织器将使“整体”看起来像:“holaholaholahola ....”并且您的程序最终会耗尽堆栈内存,这可能是您获得无效字符串位置错误的原因。另外,作为一般规则,我会避免使用静态变量。如果您按如下所示更改程序,则可能有效:

void Class::reader(string x){
    char symbol = x.at(place);
    while (symbol != '\0'){
       place++;
       replacer(symbol);
       reader(x);
       symbol = x.at(place);
   }
}