Wednesday 22 May 2019

Java: Shuffle characters in a string


'Collection.shuffle' method can be used to shuffle characters in a string.

public static void shuffle(List<?> list)
public static void shuffle(List<?> list, Random rnd)

Example
public static String shuffleString(String string) {
         List<String> letters = Arrays.asList(string.split(""));
         Collections.shuffle(letters);
         StringBuilder builder = new StringBuilder();
         for (String letter : letters) {
                  builder.append(letter);
         }
         return builder.toString();
}

App.java
package com.sample.app;

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

public class App {

 public static String shuffleString(String string) {
  List<String> letters = Arrays.asList(string.split(""));
  Collections.shuffle(letters);
  StringBuilder builder = new StringBuilder();
  for (String letter : letters) {
   builder.append(letter);
  }
  return builder.toString();
 }

 public static void main(String args[]) throws Exception {
  String str = "Hello Wolrd";
  String result = shuffleString(str);

  System.out.println("Actual String : " + str);
  System.out.println("Shuffled String : " + result);
 }
}

Sample Output
Actual String : Hello Wolrd
Shuffled String : eHdolWll ro


You may like

No comments:

Post a Comment