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

后端 未结 14 2266
南旧
南旧 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 08:08

    Not sure why you wouldn't want to use shuffle, unless it's for school. ;)

    And if you're concerned with performance, you definitely can't use any solution that concatenates strings with "+".

    Here's the most compact solution I could come up with:

    public static String shuffle(String string) {
        if (StringUtils.isBlank(string) {
            return string;
        }
    
        final List randomChars = new ArrayList<>();
        CollectionUtils.addAll(randomChars, ArrayUtils.toObject(string.toCharArray()));
        Collections.shuffle(randomChars);
        return StringUtils.join(randomChars, "");
    }
    

提交回复
热议问题