如何将某个字符串的第一个字符放在字符串中间

时间:2018-11-19 16:38:23

标签: java

示例:从字符转换为ahcrs

这是我的代码,几乎没有修改:

String word = JOptionPane.showInputDialog(null, "Input something: ");
    int check = word.length();
    if (check < 3) {
        JOptionPane.showMessageDialog(null, "Your input is invalid!");

1 个答案:

答案 0 :(得分:0)

char的值保存在临时变量中。

char firstChar = word.charAt(0); // In your case this will be 'c'
// chars (length is 5; subtract 1 to make it 0 indexed)
char middleChar = word.charAt((word.length-1) / 2); // In your case this will be 'a'

// StringBuilder provides many functions for string manipulation
StringBuilder newWord = new StringBuilder(word);
// Replacing 'c' with the middleChar 'a'
newWord.setCharAt(0, middleChar);
// Replacing 'a' with the firstChar 'c'
newWord.setCharAt((word.length-1) / 2, firstChar);