Freddy Vilches
Freddy Vilches

Reputation: 35

DART: how can i reorder randomly characters in a string?

how can i change randomly the character orders in a string?

example, Input: hello - Output: elolh

Upvotes: 1

Views: 397

Answers (1)

Augustin R
Augustin R

Reputation: 7799

You can use List.shuffle :

var text = 'HELLO';

// First turn you text into a List :
List list = text.split('');

// Shuffle the list :
list.shuffle();

// Then turn back the list into a String
String shuffled = list.join();

print(shuffled); // LLHOE

One-liner :

String shuffled = ('HELLO'.split('')..shuffle()).join();

Extension method :

void main() {
  var text = 'HELLO';
  var shuffled = text.shuffled();
  print(shuffled); // OLEHL
}


extension on String {
  String shuffled() =>
    (this.split('')..shuffle()).join();
}

Upvotes: 4

Related Questions