c++ - 将一个数组中的字符替换为另一个数组中的字符串

标签 c++ arrays string replace

我希望使用带有 replace(str.begin(), str.end(), "x", "y") 的 for 循环会很简单,但是 "x ""y" 是数组中的某个字符,所以: replace(str.begin(), str.end(), arrX[1], arrY[ 1]) 在循环中:

for (int i = 0; i < arraySize; i++) {
    replace( str.begin(), str.end(), arrX[i], arrY[i]);
}

但是在我的代码中:

#include <iostream>
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

string Caesar(string str) { 
  char alph[]   = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
  string caesar = "abcdefghijklmnopqrstuvwxyz";
  const int arraySize=sizeof(alph)/sizeof(alph[0]);
  rotate(caesar.begin(), caesar.begin()+3, caesar.end());
  for (int i = 0; i < arraySize; i++) {
    replace(str.begin(), str.end(), alph[i], caesar[i]);
  }
  return str; 
}
int main() {
  cout << Caesar("hello");
}

caeser 字符串按 alph 旋转三位。

输出 caesar 给出了预期的结果。 (abcdef ... 变成 xyzabc ... 当只打印 caesar 时。)

我的循环似乎把事情搞砸了,当给定 hello 时,它会生成 ccaaa。我测试了替换一个字母并且成功了,但问题似乎出在我的 for 循环上,但我似乎无法找出问题所在。

更新:

我找到了一种支持非字母字符的方法,使用 while 循环检查它是否按字母顺序排列,然后遍历字母表,将每个字母与字符串中的字母进行比较,直到它们匹配,然后将其替换为旋转的凯撒字母表,如果它们不匹配,它会转到下一个,当找到它时,它会将 'j' 重置为 0,这样它可以通过递增 'i' 为下一个字母再次执行此操作,如果字符不是letter 它只是将'i'增加到下一个字符以跳过它直到它到达新字母或字符串的末尾。

#include <iostream>
#include <algorithm>

using namespace std;

bool IsInArray(string array, char element) {
  for(int i = 0; i < array.length(); i++){
     if(array[i] == element){
         break;
     }
  }
}
string rot(int n, string str) {
  transform(str.begin(), str.end(), str.begin(), ::tolower);
  string alph = "abcdefghijklmnopqrstuvwxyz";
  string ciph = alph;
  rotate(ciph.begin(), ciph.begin() + n, ciph.end());

  int i = 0;
  int j = 0;
  while (i < str.length()) {
    if (IsInArray(alph, str[i])) {
      if (str[i] == alph[j]) {
        str[i] = ciph[j];
        i++;
        j = 0;
      }
      else {
        j++;
      }
    }
    else {
      i++;
    }
  }
  return str;
}

int main() {
  cout << rot(2, "This cipher works with more than just alpha chars!");
  return 0;
}

最佳答案

这是一种使用标准函数和 lambda 函数的方法:

string Caesar(std::string str) { 
    std::string caesar = "abcdefghijklmnopqrstuvwxyz";
    std::rotate(caesar.begin(), caesar.end()-3, caesar.end());
    std::transform(str.begin(), str.end(), str.begin(), 
        [caesar](char c) -> char { return caesar[c - 'a']; });
    return str; 
}

注意:它使用字符代码来获取索引,因此必须更改它以处理除“abc...xyz”以外的任何内容。

关于c++ - 将一个数组中的字符替换为另一个数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41387715/

相关文章:

c++ - CMake 使用 32 位或 64 位编译器

java - 当我将二维数组向左移动超过两次时,它会替换其中一个数字

javascript - 检查数组的所有值是否都在特定数字之下

java - 字符串到字符数组和字符串数组

python - Django 'str' 对象不可调用。如何处理?

java - 我到底什么时候应该使用 StringBuilder 而不是 String

c++ - 恢复 OpenGL 状态

c++ - 为什么 type_info 在命名空间 std 之外声明?

python - 将二维数组保存为 txt 文件

c++ - 避免前向重新声明。这是一个好习惯吗?有必要吗?