How to shuffle a string in Java

1 Answer

0 votes
import java.util.List;
import java.util.Arrays;
import java.util.Collections;

public class MyClass {
    public static String shuffleString(String s) {
      List<String> chars = Arrays.asList(s.split(""));
      Collections.shuffle(chars);
      
      String shuffled = "";
      for (String ch : chars) {
        shuffled += ch;
      }
      
      return shuffled;
    }
    public static void main(String args[]) {
        String s = "java c++ php python";
        
        s = shuffleString(s);
        
        System.out.println(s);
    }
}




/*
run:

cjhnpyta+ov p pah+

*/

 



answered Mar 28, 2021 by avibootz

Related questions

2 answers 173 views
173 views asked Nov 8, 2023 by avibootz
2 answers 139 views
139 views asked Mar 25, 2023 by avibootz
2 answers 162 views
162 views asked Oct 30, 2021 by avibootz
1 answer 165 views
165 views asked Mar 29, 2021 by avibootz
1 answer 277 views
277 views asked Mar 15, 2021 by avibootz
1 answer 183 views
1 answer 95 views
95 views asked Nov 5, 2024 by avibootz
...