Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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, first, last){
    var temp = arr[first];    
    arr[first] = arr[last];
    arr[last] = temp;
}
like image 351
Vandana Bhat Avatar asked Aug 16 '14 23:08

Vandana Bhat


People also ask

Can we swap characters in a string?

As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created).

How do you switch elements in a string?

Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time.


3 Answers

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('');
}
like image 87
Oriol Avatar answered Sep 25 '22 20:09

Oriol


Let me offer my side of what I understood: swapping items of an array could be something like:

var myFish = ["angel", "clown", "mandarin", "surgeon"];
var popped = myFish.pop();
myFish.unshift(popped) // results in ["surgeon", "angel", "clown", "mandarin"]

Regarding swaping first and last letters of an strings could be done using Regular Expression using something like:

"mandarin".replace(/^(\w)(.*)(\w)$/,"$3$2$1")// outputs nandarim ==> m is last character and n is first letter
like image 27
Dalorzo Avatar answered Sep 24 '22 20:09

Dalorzo


I just ran your code right out of Chrome, and it seemed to work find for me. Make sure the indices you pass in for "first" and "last" are correct (remember JavaScript is 0-index based). You might want to also try using console.log in order to print out certain variables and debug if it still doesn't work for you.

EDIT: I didn't realize you were trying to manipulate a String; I thought you just meant an array of characters or values.

My code

like image 27
Zexus Avatar answered Sep 21 '22 20:09

Zexus