How to swap String characters in Java?

后端 未结 14 2249
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 14:22

How can I swap two characters in a String? For example, \"abcde\" will become \"bacde\".

14条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 14:59

    This has been answered a few times but here's one more just for fun :-)

    public class Tmp {
        public static void main(String[] args) {
            System.out.println(swapChars("abcde", 0, 1));
        }
        private static String swapChars(String str, int lIdx, int rIdx) {
            StringBuilder sb = new StringBuilder(str);
            char l = sb.charAt(lIdx), r = sb.charAt(rIdx);
            sb.setCharAt(lIdx, r);
            sb.setCharAt(rIdx, l);
            return sb.toString();
        }
    }
    

提交回复
热议问题