How to Reverse a String in Dart (3 Approaches)

Updated: March 31, 2023 By: A Goodman 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).

Turn the String into an Array

Example:

// 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

Using StringBuffer

Example:

// 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

Using Char Code Technique

Example:

// 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

Related Articles