0

I am writing a Java program to encrypt a four digit number. Some procedures require to swap 1st digit with 3rd and 2nd with 4th... Here's what I have written, but it's not working. for example, if my input is 9876 then after these four swaps it gives output 9898. which means that first and third Swaps are not working. But if I comment the second and fourth swaps then 1st and 3rd swap works.

 char ch;
 ch=str.charAt(0);
        str=str.replace(str.charAt(0),str.charAt(2));
        str=str.replace(str.charAt(2),ch);


        ch=str.charAt(1);
        str=str.replace(str.charAt(1),str.charAt(3));
        str=str.replace(str.charAt(3),ch);

2 Answers 2

2

Retrieve the internal character array of your String instance by a call to toCharArray() and then swap the particular elements of that char array with a robust helper swap() method. Then convert your modified char array back to a String.

Sign up to request clarification or add additional context in comments.

Comments

1

You can also use substring, eg:

str = str.substring(2,3) + str.substring(3,4) + str.substring(0,1) + str.substring(1,2);

Change last Two digits with first two is also equivalent (it fits your case and it's faster):

str = str.substring(2,4) + str.substring(0,2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.