Reputation: 35
how can i change randomly the character orders in a string?
example, Input: hello - Output: elolh
Upvotes: 1
Views: 397
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