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

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

    What an annoying problem. I finally ended up with this:

    import java.util.Collections;
    import com.google.common.primitives.Chars;
    import org.apache.commons.lang3.StringUtils;
    
    String shuffle(String s) {
        List chars = Chars.asList(s.toCharArray());
        Collections.shuffle(chars);
        return StringUtils.join(chars.stream().toArray());
    }
    

    Yes, two libraries :)

提交回复
热议问题