How to Reverse a String in Dart (3 Approaches)

Last updated on June 22, 2022 A Goodman Loading... Post a comment

The three examples below show you three different ways to reverse a given string in Dart (e.g. turn ABC to CBA).

Example 1

// KindaCode.com
// main.dart

// Define a reusable function
String reverseString(String input) {
  final output = input.split('').reversed.join('');
  return output;
}

void main() {
  // Try it
  print(reverseString('ABCDEFGH'));
  print(reverseString('The busy dog jumps over the lazy dog'));
}

Output:

HGFEDCBA
god yzal eht revo spmuj god ysub ehT

Example 2

// Define a reusable function
String reverseString(String input) {
  var buffer = StringBuffer();
  for (var i = input.length - 1; i >= 0; --i) {
    buffer.write(input[i]);
  }
  return buffer.toString();
}

void main() {
  // Try it
  print(reverseString('123456789'));
  print(reverseString('Welcome to KindaCode.com'));
}

Output:

987654321
moc.edoCadniK ot emocleW

Example 3

// Define a reusable function
String reverseString(String input) {
  String reversedString = String.fromCharCodes(input.codeUnits.reversed);
  return reversedString;
}

void main() {
  // Test it
  print(reverseString('banana'));
  print(reverseString('Welcome to KindaCode.com'));
}

Output:

ananab
moc.edoCadniK ot emocleW

Futher reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like