Dart 串列有一種.shuffle()以隨機順序重新排列專案的方法。有沒有一種簡單的方法可以像這樣對字串中的字符進行隨機播放?
uj5u.com熱心網友回復:
String.split('')如果要重新排列結果中的元素,請注意使用Unicode 字串List。split('')將分割一個StringUTF-16 代碼單元邊界。例如,'\u{1F4A9}'.split('')將回傳List兩個元素中的 a,重新排列它們并重新組合它們將導致字串損壞。
通過拆分 Unicode 代碼點,使用String.runes會更好一些:
extension Shuffle on String {
String get shuffled => String.fromCharCodes(runes.toList()..shuffle());
}
更好的是用于package:characters對字素集群進行操作:
extension Shuffle on String {
String get shuffled => (characters.toList()..shuffle()).join();
}
uj5u.com熱心網友回復:
list 方法修改一個串列,.shuffle()使其元素處于隨機順序。與串列不同,字串在 Dart 中是不可變的,因此不可能有一個.shuffle()字串方法可以做同樣的事情。
幸運的是,您可以只使用一個回傳混洗字串的函式來獲得相同的效果:
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('');
}
這是在行動:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/496451.html
上一篇:如何將串列傳遞給另一個班級
下一篇:提供者:如何在`StreamBuilder()`中`notifyListener()`?它會導致錯誤“setState()或markNeedsBuild()在構建期間呼叫”
