1

Dart lists have a .shuffle() method that rearranges the items in a random order. Is there an easy way to shuffle characters in a string like this?

2 Answers 2

3

Beware of using String.split('') on Unicode strings if you're going to rearrange elements in the resulting List. split('') will split a String on UTF-16 code unit boundaries. For example, '\u{1F4A9}'.split('') will return a List of two elements, and rearranging them and recombining them will result in a broken string.

Using String.runes would work a bit better by splitting on Unicode code points:

extension Shuffle on String {
  String get shuffled => String.fromCharCodes(runes.toList()..shuffle());
}

Even better would be to use package:characters to operate on grapheme clusters:

extension Shuffle on String {
  String get shuffled => (characters.toList()..shuffle()).join();
}
Sign up to request clarification or add additional context in comments.

Comments

2

The .shuffle() list method modifies a list so that its elements are in a random order. Unlike lists, string are immutable in Dart, so it's impossible to have a .shuffle() method for strings that does the same thing.

Luckily, you can just use a function that returns a shuffled string to get the same effect:

extension Shuffle on String {
  /// Strings are [immutable], so this getter returns a shuffled string
  /// rather than modifying the original.
  String get shuffled => (split('')..shuffle()).join('');
}

Here it is in action:

final list = [1, 2, 3];
list.shuffle(); // list is now in random order

var str = 'abc';
str = str.shuffled; // str is now in random order

1 Comment

This won't work well on Unicode strings. See my answer for better approaches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.