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

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

    Without external libraries, for those who do not mind using Collections.shuffle():

    static String shuffle(String string){
    
        List<Character> list = string.chars().mapToObj(c -> new Character((char) c))
                                             .collect(Collectors.toList());
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        list.forEach(c -> sb.append(c));
    
        return sb.toString();
    }
    
    0 讨论(0)
  • 2020-11-27 08:20
    import java.util.Random;
    
    public class carteRecharge {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String characters = "AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn1234567890";
    
            Random rand = new Random();
    
            //Nombre de caratère à tirer 
            int length = 20;
    
            //La variable qui contiendra le mot tire
            String randomString = "";
    
            //
            char[] text = new char[length];
    
            for(int i = 0; i < length; i++) {
                text[i] = characters.charAt(rand.nextInt(characters.length()));
    
            }
    
    
            for(int i=0; i<text.length; i++) {
                randomString += text[i];
            }
    
            System.out.print(randomString);
    
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题