Today, I had some free time to come back to our on-going Flutter projects. One of my tasks was “reverse a string”, easy enough, right? Without thinking I typed the code confidently, but I was very surprised, Dart does not support any method to reverse a string. Haha, are you kidding me, Dart?
I still didn’t believe that, I did some searches on the internet and I ended-up to find some ways to just “reverse a string in Dart”. I am happy to share them here:
Use split and join:
String reverseStringUsingSplit(String input) {
var chars = input.split('');
return chars.reversed.join();
}
Use runes:
String reverseStringUsingRunes(String input) {
var chars = input.runes.toList();
return String.fromCharCodes(chars.reversed);
}
Use codeUnits:
String reverseStringUsingCodeUnits(String input) {
return String.fromCharCodes(input.codeUnits.reversed);
}
I don’t really understand why Dart ignore this basic method. But it is interesting to implement reverse method ourself, isn’t it? Let’s put all the code together:
void main() {
var coflutter = 'Coflutter';
print(reverseStringUsingSplit(coflutter));
print(reverseStringUsingRunes(coflutter));
print(reverseStringUsingCodeUnits(coflutter));
}
String reverseStringUsingSplit(String input) {
var chars = input.split('');
return chars.reversed.join();
}
String reverseStringUsingRunes(String input) {
var chars = input.runes.toList();
return String.fromCharCodes(chars.reversed);
}
String reverseStringUsingCodeUnits(String input) {
return String.fromCharCodes(input.codeUnits.reversed);
}
// Output
rettulfoC
rettulfoC
rettulfoC