我需要编写一个方法,将字符串的第一个和最后一个字母交换位置。例如,字符串"java"将变为"aavj"。
以下是我的代码:
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);
}
}
使用这段代码,当我输入“java”时,输出结果是“ajavaj”,那么我该如何修复它?我需要交换前两个字母并仍保留字符串的中间部分。我应该怎么做?
char
数组的解释不太合理,因为你无论如何都要创建一个新的字符串。虽然可以说这样做可以少创建一个字符串实例,但这并不足以成为在这里使用char
数组的有力论据。 - Makotopassword = lastChar + password + firstChar;
除了原始代码中的firstChar
和lessChar
之外,还创建了一个新的字符串。 - user2004685