How to shuffle characters in a string without using Collections.shuffle(…)?

后端 未结 14 2272
南旧
南旧 2020-11-27 07:19

How do I shuffle the characters in a string (e.g. hello could be ehlol or lleoh or ...). I don\'t want to use the Collections.shuffle(...) method, is there anyt

14条回答
  •  悲哀的现实
    2020-11-27 07:58

    How about this:

    public static String shuffle(String text) {
        char[] characters = text.toCharArray();
        for (int i = 0; i < characters.length; i++) {
            int randomIndex = (int)(Math.random() * characters.length);
            char temp = characters[i];
            characters[i] = characters[randomIndex];
            characters[randomIndex] = temp;
        }
        return new String(characters);
    }
    

提交回复
热议问题