OneBite.Dev - Coding blog in a bite size

Trim A String In Dart

Code snippet for how to Trim A String In Dart with sample and detail explanation

In Dart, just like any other programming language, trim is an essential operation that helps in removing spaces or extraneous characters from the string input’s beginning and end. This article will guide you through the process of how to trim a string in Dart.

Code snippet for trimming a string in Dart

In Dart, trimming a string is a swift process, kindly see the code snippet below:

void main() {
  String str = "   Hello World!   ";
  print(str.trim());
}

When you run this Dart code, the output will be:

Hello World!

This is because the trim() method helps remove the extra spaces at the beginning and end of the string.

Code Explanation on trimming a string in Dart

In Dart, to trim a string, we use the trim() method. The trim() method is a built-in function in Dart that enables the removal of all trailing and leading white spaces from a string object.

From our code snippet above, str is the string variable that we want to trim. It was initially assigned the string " Hello World! ", which has leading and trailing spaces. When the trim() method is called on the str variable (i.e., str.trim()), it operates by going through the string from both ends and removes white spaces until it encounters a non-white space character.

In our case, " Hello World! " becomes "Hello World!" after trimming. The spaces inside the string, however, will remain unaffected by the trim() function. Therefore, the space between “Hello” and “World!” remains intact even after trimming.

After calling str.trim(), the resulting string "Hello World!" is then printed out in the console, without the leading and trailing white spaces.

As you can see, the trim function is a useful utility function in Dart that provides an easy way to clean up your strings, especially when dealing with user input or data from databases where extra white spaces could cause confusion or mistakes in your code.

dart