How can I shuffle the letters of a word?

Viewed 32449

What is the easiest way to shuffle the letters of a word which is in an array? I have some words in an array and I choose randomly a word but I also want to shuffle the letters of it.

public static void main (String[] args ) {
    String [] animals = { "Dog" , "Cat" , "Dino" } ;    
    Random random = new Random();
    String word = animals [random.nextInt(animals.length)];

    System.out.println ( word ) ;
    //I Simply want to shuffle the letters of word     
}

I am not supposed to use that List thing. I've come up with something like this but with this code it prints random letters it doesn't shuffle. Maybe I can code something like do not print if that letter already printed?

//GET RANDOM LETTER
for (int i = 0; i< word.length(); i++ ) {

char c = (word.charAt(random.nextInt(word.length())));
System.out.print(c); } 
  }
4 Answers

Shuffle String Using Collection.

import java.util.*;

public class ShuffleString {
    
    public static void main(String[] args) {
        
        String str = "Team India Is Best";
        String shuf = "";
        String s1 = str.substring(0, 4);
        String s2 = str.substring(5, 10);
        String s3 = str.substring(11, 13);
        String s4 = str.substring(14, 18);
        ArrayList<String> arr = new ArrayList<String>();
        arr.add(s1);
        arr.add(s2);
        arr.add(s3);
        arr.add(s4);
        Collections.shuffle(arr);

        for(String a : arr)
        {
            shuf += a + " ";
        }
        System.out.println(shuf);
    }
}
Related