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

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

    class ShuffleString
    {
    
        public static String shuffle(String s)
        {
    
            String shuffledString = ""; 
    
            while (s.length() != 0)
            {
                int index = (int) Math.floor(Math.random() * s.length());
                char c = s.charAt(index);
                s = s.substring(0,index)+s.substring(index+1);
                shuffledString += c;
            }
    
            return shuffledString;
    
        }
    
    }
    
    
    public class foo{
        static public void main(String[] args)
        {
    
            String test = "hallo";
            test = ShuffleString.shuffle(test);
            System.out.println(test);
        }
    }
    

    Output: ahlol

提交回复
热议问题