How to swap String characters in Java?

后端 未结 14 2259
佛祖请我去吃肉
佛祖请我去吃肉 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:53

    //this is a very basic way of how to order a string alpha-wise, this does not use anything fancy and is great for school use

    package string_sorter;

    public class String_Sorter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    
        String word = "jihgfedcba";
        for (int endOfString = word.length(); endOfString > 0; endOfString--) {
    
            int largestWord = word.charAt(0);
            int location = 0;
            for (int index = 0; index < endOfString; index++) {
    
                if (word.charAt(index) > largestWord) {
    
                    largestWord = word.charAt(index);
                    location = index;
                }
            }
    
            if (location < endOfString - 1) {
    
                String newString = word.substring(0, location) + word.charAt(endOfString - 1) + word.substring(location + 1, endOfString - 1) + word.charAt(location);
                word = newString;
            }
            System.out.println(word);
        }
    
        System.out.println(word);
    }
    

    }

提交回复
热议问题