I am manipulating ssn.
Input =”123456789″
Output=”896745123″
You take the first 3 digits from the input (i.e 123) and swap it with the last two digits “89” and then swap “45” with “67”. Below is the code I have using toCharArray. But I didn’t like it. This method (not the test) can be accessed by many users at a time. I was looking for a better in performance, readability and trade safe solution.
I appreciate your help.
@Test
public void testSSNString(){
String original="123456789";
String result="896745123";
char[] charResult=original.toCharArray();
char temp=charResult[6];
charResult[6]=charResult[0];
charResult[0]=charResult[7];
charResult[7]=charResult[1];
charResult[1]=charResult[8];
charResult[8]=charResult[2];
charResult[2]=charResult[5];
charResult[5]=charResult[4];
charResult[4]=charResult[3];
charResult[3]=temp;
assertEquals(original.toCharArray(),charResult);
}
The way that you have given is essentially the best you can do in Java in terms of performance. Using arrays is faster than using
StringBuilder.To improve readability, I would just make some small changes, like making a new array for the permuted output: