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('');
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…