Trim a string in Dart : Explanation with examples

Published by admin on

Dart trim a string explanation & examples

Introduction :

Trim a string means removing the extra white spaces at the end of the string or at the start of the string. Trim is really useful if you don’t want that extra white space. If you are comparing one string value in your application with a value you are getting from the server, it will be a problem if the server is sending strings with leading or trailing white spaces. For example,if you are comparing “hello” in your application with a string you will get from the server and if the server sends “hello “, the comparison may fail if you are not removing the trailing blank spaces.

Dart provides three different methods in the String class to trim a string. In this tutorial, we will learn how to do that with an example.

 

Following are the methods used to trim a string in Dart:

1. trim() → String :

This method removes the white spaces from both sides of a string. As the string is immutable in dart, it can’t modify the original string. It creates one new string and returns it.

2. trimLeft() → String :

This method removes the white spaces from the start of a string. It also returns the modified string.

trimRight() → String :

This method removes the white spaces from the end of a string. It returns the modified string as like the above one.

 

Example :

Let’s test the above methods with a small example :

void main() {
  String message = "      Hello       ";
  print("***" + message.trimRight() + "***");
  print("***" + message.trimLeft() + "***");
  print("***" + message.trim() + "***");
}

Output :

***      Hello***
***Hello       ***
***Hello***

dart trim string

Explanation :

As you can see here, the first print statement uses trimRight to trim the right white spaces, left in the second print statement and both in the third print statement.

trim() is the most commonly used method than the other two.

 

Conclusion :

In this example, we have learned how to trim a string in Dart. Try to go through the example and drop one comment below if you have any queries.

Categories: dart

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *