Why can't I swap characters in a javascript string?

后端 未结 4 1388
無奈伤痛
無奈伤痛 2020-12-11 02:35

I am trying to swap first and last characters of array.But javascript is not letting me swap. I don\'t want to use any built in function.

function swap(arr         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 03:16

    Because strings are immutable.

    The array notation is just that: a notation, a shortcut of charAt method. You can use it to get characters by position, but not to set them.

    So if you want to change some characters, you must split the string into parts, and build the desired new string from them:

    function swapStr(str, first, last){
        return str.substr(0, first)
               + str[last]
               + str.substring(first+1, last)
               + str[first]
               + str.substr(last+1);
    }
    

    Alternatively, you can convert the string to an array:

    function swapStr(str, first, last){
        var arr = str.split('');
        swap(arr, first, last); // Your swap function
        return arr.join('');
    }
    

提交回复
热议问题