Dart| Flutter How to reverse a string example
In this article, learn how to reverse a string in multiple ways. It also includes reversing a string with Unicode UTF-8 characters.
There are multiple ways we can do it. Dart provides an inbuilt dart:convert
library to encode and decode various objects in UTF8 formats.
How to do string in reverse order in dart
This example takes the input string and converts the string in reverse order.
- First, the Given string is split into characters using the
split()
method. and It returns a List of characters. - List is reversed using the
reversed
property - Finally, join the list of characters using the join() method
here is an example code to reverse a string in a dart.
import 'dart:convert';
main() {
final str = "Welcome to my site";
print(str); //Welcome to my site
print(str.split('').reversed.join()); // etis ym ot emocleW
}
Output:
Welcome to my site
etis ym ot emocleW
The above example only works with ASCII text.
It will not work If you want to convert UTF-8 strings in reverse order.
How to convert Unicode strings in reverse order?
This example converts a Unicode string that contains emojis and code units into reverse order.
There are multiple ways we can do
The first way, Using code units
.
- First, get codeunits of a string using the
codeUnits
property, which returns UTF-16 code units of each character in a string. - Reverse the code unit string using the
reversed
property. - Convert and create a new string from a given codeunit iterable character using the
fromCharCodes
method Here is an example code
main() {
var unicodeString = "unicode string \u{231B}"; //unicode string ⌛
print(unicodeString); //unicode string ⌛
print(String.fromCharCodes(unicodeString.codeUnits.reversed)); //⌛ gnirts edocinu
}
The second way, using runes
runes
is a type that represents a Unicode character.
- First, get codeunits of a string using the
runes
property, returns a list of code units of each character in a string using thetoList()
method - Reverse the code unit list using the
reversed
property. - Convert and create a new string from a given codeunit iterable character using the
fromCharCodes
method Here is an example code
main() {
var unicodeString = "unicode string \u{231B}"; //unicode string ⌛
print(unicodeString); //unicode string ⌛
var runeChars = unicodeString.runes.toList();
print(String.fromCharCodes(runeChars.reversed));⌛ gnirts edocinu
}
Conclusion
To summarize,
Learned how to convert a string or ASCII and Unicode characters into reverse order.