【问题标题】:How to swap character positions in a string JavaScript如何交换字符串 JavaScript 中的字符位置
【发布时间】:2021-10-05 23:39:32
【问题描述】:

我正在制作一个解密函数,但我被困在需要交换 第二个字母和字符串最后一个字母的位置的部分。 我也尝试过使用替换方法,但我认为应该使用子字符串。

Hello 应该等于 Holle 等

function decipher(str) {
  let s = ""
  for (let word of str.split(" ")){
    let dig = word.match(/\d+/)[0]
    word = word.replace(dig, String.fromCharCode(dig))
    let secondLetter = word[1]
    let lastLetter = word[word.length - 1]
    let swapped = word.substring(0,1) + lastLetter + word.substring(2,3) + secondLetter
    s += swapped + " "
  }
  return s
}; 

【问题讨论】:

  • 不能直接交换吗?将第二个字母放在一个临时变量中,然后将最后一个字母分配给第二个字母,然后将临时变量分配给最后一个字母

标签: javascript string replace substring swap


【解决方案1】:

请更改此行:

let swapped = word.substring(0,1) + lastLetter + word.substring(2,word.length - 1) + secondLetter;

【讨论】:

  • 我知道那行是问题所在,它只适用于 4 个字母的字符串,我正在寻找一种适用于所有长度的字符串的替代方法
【解决方案2】:

考虑将其提取到一个函数中以保持代码库更清晰:

function swapSecondAndLastLetter(str) {
   // Split the string into a mutable array
   let original = str.split('');

   original[1] = str[str.length-1];
   original[original.length-1] = str[1];

   // Join the mutable array back into a string
   return original.join('');
}

【讨论】:

    【解决方案3】:

    如果仅针对特定用例(即交换第二个和最后一个),您可以使用简单的正则表达式 -

    正则表达式 -(.)(.)(.*)(.)

    const str = "Hello";
    console.log(swap(str));
    
    function swap() {
      return str.replace(/(.)(.)(.*)(.)/, "$1$4$3$2")
    }

    【讨论】:

      【解决方案4】:

      你可以解构字符串:

      const swap = ([a, b, ...xs]) => [a, xs.pop(), ...xs, b].join('');
      //                                  ^^^^^^^^         ^
      //                                  |____swapping____|
      
      swap("Hello");
      //=> "Holle"
      

      通过解构,您还将支持表情符号(但可能不支持字形):

      swap("H?ll?");
      //=> "H?ll?"
      

      在字符串中交换单词:

      const decipher = str => str.split(' ').map(swap).join(' ');
      
      decipher("Hello World");
      //=> "Holle Wdrlo"
      
      decipher(decipher("Hello World"));
      //=> "Hello World"
      

      为什么要解构?

      通过索引或(简单)正则表达式读取字符串中的字符可能不适用于多代码点字符,例如(但不限于)表情符号:

      "?".length;
      //=> 2! Not 1.
      
      "?".charAt(0);
      //=> "\ud83c"! Not "?".
      

      考虑这个swap 函数:

      function swap(str) {
        var arr = str.split('');
        var [a, b] = [arr[1], arr[arr.length-1]];
        arr[1] = b;
        arr[arr.length-1] = a;
        return arr.join('');
      }
      

      适用于普通的旧 ASCII:

      swap("Hello");
      //=> "Holle"
      

      表情符号无法正常工作:

      swap("H?ll?");
      //=> "H\udf63\udf2fll\ud83c\ud83c"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多