Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

What is the String.trim method in Dart?

Anitha

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The trim method can be used to remove all the leading and trailing whitespace present in the string.

Syntax

String trim()

Return value

This method returns a new string without any leading and trailing whitespace present in the calling string.

Note: A list of the characters that will be trimmed by the trim method can be found here.

Code

The code below demonstrates how we can use the trim method in Dart.

void main() {
//create a string with whitespaces
var str = " \n\n\t this \t is a test \t\n ";
print('str with whitespace :$str');
var trimmedString = str.trim();
print('TrimmedString : $trimmedString');
}
Using the "trim" method to remove whitespaces

Code explanation

In the code given above:

In line 3, we create a new string, str, with some whitespaces at the start and end of the string. The whitespace includes a new-line character (\n) and a tab character (\t).

In line 5, we use the trim method to remove the whitespace at the start and end of the string. This method returns a new string, which will be stored in trimmedString.

In line 6, we print trimmedString. trimmedString will not have any whitespace at the start or end of the string.

Note: Only the whitespace at the beginning and end of the string is removed. The whitespace between the string is not removed.

RELATED TAGS

dart
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring