how to reverse a string in dart
flutter reverse string

How to Reverse a String in Dart (3 Approaches)

Hi Guys, Welcome to Proto Coders Point, In this Dart article let’s learn how can we reverse a string in dart.

Below are the three different ways to reverse a given string in dart programming language. For Example: (XYZ –> Convert to ZYX). By reversing a string you can check if a given string is palindrome or not.

Let’s get Started

Example 1 – Reverse strig using in-built reversed method

//PROTOCODERSPOINT
// A Function that reverse a given string.

String reverseAString(String input) {
  final output = input.split('').reversed.join('');

  return output;
}

void main() {
  print(reverseAString('NITIN'));
  print(reverseAString('"We are what we think." — Buddha'));
}

Output:

NITIN
ahdduB — ".kniht ew tahw era eW"


Example 2 – String reverse using String.fromCharCodes & codeUnits.

//PROTOCODERSPOINT
// A Funcion that reverse a given string using  codeUnits & fromCharCodes methods.

String reverseAString(String input) {
 String reversedString = String.fromCharCodes(input.codeUnits.reversed);
  return reversedString;
}

void main() {
  print(reverseAString('ROTATOR')); 
  print(reverseAString('Live life to the fullest.'));
}

Output:

ROTATOR
.tselluf eht ot efil eviL


Example 3 – Reverse a String using reverse for loop & buffer writter.

//PROTOCODERSPOINT
// A Funcion that reverse a given string using reverse for loop.

String reverseAString(String input) {
  var buffer = StringBuffer();
  for (var i = input.length - 1; i >= 0; --i) {
    buffer.write(input[i]);
  }
  return buffer.toString();
}

void main() {
  print(reverseAString('NITIN'));
  print(reverseAString('Imagination is greater than detail'));
}

Output:

NITIN
liated naht retaerg si noitanigamI


Recommended Article

How to reverse a string and check if its a palindrome