How to Shuffle String Value? (JAVA ANDROID)

Asked

Viewed 49 times

-2

The thing is, I’m creating an android app and I prescribe shuffle the value of a string.

Example:

String name = "Bruno";

Shuffles the string value(name).

Output: "ronub"

  • Hello Bruno all right, try to formulate your questions in a way that makes clear your doubt. What you have done or tried. Expose the code where you have the doubt, so it’s easier to help.

1 answer

-1


This function will solve:

    public static String shuffle(String text) {
        Random random = new Random();
        List<Character> collect = text.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
        List<Character> newList = new ArrayList<>();
        while (collect.size() > 0) {
            Character character = collect.remove(random.nextInt(collect.size()));
            newList.add(character);
        }
        StringBuilder sb = new StringBuilder();
        for (Character c : newList) {
            sb.append(c);
        }
        return sb.toString();
    }

for example 10 times with my name "Thiago Born" and the results were:

oTaon hgBri
onogBirTh a
r iaghoTBno
ronBTgiao h
BigTo hanro
Ta noBhorgi
oBnTg ahori
onhTgBir oa
hBro aigTno
ahrB Toigno
  • what would be the reason for downvote? the answer is exactly what the user wants

Browser other questions tagged

You are not signed in. Login or sign up in order to post.