将所有字符替换为一组字符

Replace All Characters with a set of characters

本文关键字:字符 一组 替换      更新时间:2023-10-16

我试图用另一组字符替换字符串中的每个字符

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 != ''){
       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;
}

当我试图在测试字符串中只使用"a"运行它时,我一直得到一个无效的字符串位置作为错误。

在while循环中,'symbol'下面总是'a'。

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

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

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