Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching the first and last letter of a string in Java?

Tags:

java

string

I have to write a method to switch the first and last letter of a string. For example the string "java" would become "aavj".

Here is what I have so far:

import javax.swing.JOptionPane;

public class printTest {
    public static void main(String[] args) {
        String password;
        password = JOptionPane.showInputDialog("Please input your password");
        int length = password.length();
        String firstChar = password.substring(0, 1);
        String lastChar = password.substring(length - 1);

        password = lastChar + password + firstChar;
        JOptionPane.showMessageDialog(null, password);
    }
}

With that code I get the following output "ajavaj" when I input "java", so how can I fix this? I need to switch the first two letters and still have the middle of the string. What should I do?

like image 284
logonin Avatar asked Dec 06 '22 19:12

logonin


2 Answers

You need to substring password on this line:

password = lastChar + password.substring(1, length-1) + firstChar;
like image 119
jheimbouch Avatar answered Dec 09 '22 13:12

jheimbouch


By doing password = lastChar + password + firstChar; you are concatenating the original password String with the two other Strings i.e. lastChar & firstChar. By doing this you will actually get a new String with lastChar and firstChar appended and not swapped.

Also, Strings are immutable and every time you are trying to manipulate it, you are ending up creating a new String. You should use char array instead to avoid this problem.

Try this piece of code:

import javax.swing.JOptionPane;
public class printTest
{
     public static void main(String[] args)
     {
          /* Capture Password */
          String password = JOptionPane.showInputDialog("Please input your password");
          char[] pass = password.toCharArray();

          /* Swap Logic */
          char temp = pass[0];
          pass[0] = pass[pass.length - 1];
          pass[pass.length - 1] = temp;

          /* Show MessageDialog */
          JOptionPane.showMessageDialog(null, new String(pass));
     }
}
like image 41
user2004685 Avatar answered Dec 09 '22 15:12

user2004685