Home > Blockchain >  How do you shuffle a string in Dart?
How do you shuffle a string in Dart?

Time:06-28

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?

CodePudding user response:

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 to split 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();
}

CodePudding user response:

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
  • Related