Skip to main content

Dart: Reverse a String

This is a simple problem where we have a string, for example, Hello world, and we need to reverse it to become dlrow olleH.

There are two ways to solve this problem, and in both, we will use a for loop to iterate character by character starting from the last character. Also, in both solutions, we will use the Runes API to access each of the characters. But one of these ways is more efficient than the other. Let's see the solutions:

Solution 1: Using a String variable

Given the text Hello world, we will create a variable of type String called reversedText to help us store the reversed text.

Then we will create a loop to iterate character by character from the last position, and we will concatenate each one to the reversedText variable.

for (var i = text.runes.length - 1; i >= 0; i--) {
reversedText += String.fromCharCode(
text.runes.elementAt(i),
);
}
info

In Dart, if we want to access the characters of a String, we have to use the Runes API. A "rune" is an integer that represents a Unicode code point.

After the loop ends, reversedText contains the text dlrow olleH, and we can print it using the print function.

The disadvantage of this solution is that the String data type is immutable, which means that the string variable cannot change, so every time we concatenate a character to reversedText, it creates a new object, consequently, we use more memory.

You can run the code for solution 1 in DartPad to see the results:

Solution 2: Using StringBuffer

This solution is very similar to the previous one, but now we will use the StringBuffer class. The advantage of using this class is that in each iteration of the loop, we will not create a new object, so this solution is more memory efficient.

Given the text Hello world, we will create a variable of type StringBuffer called reversedText to help us store the reversed text.

Then we will create a loop to iterate character by character from the last position, and we will add each one to the reversedText variable using the write function.

for (var i = text.runes.length - 1; i >= 0; i--) {
reversedText.write(
String.fromCharCode(text.runes.elementAt(i)),
);
}

After the loop ends, reversedText contains the text dlrow olleH, and we can print it using the print function.

You can run the code for solution 2 in DartPad to see the results:

Conclusion

This is a simple problem that should not take more than a couple of minutes to solve. My recommendation in a job interview is to use solution 2 with StringBuffer because it is more efficient.

If you know another way to solve this problem that is more efficient, you can leave it in the comments.