CodeBlanks Logo Icon CodeBlanks

trim and pad

Learn formatting with trim, padLeft and padRight.

trim

To remove the whitespace characters (space, tab, newline) at the start and end of a string use trim. It is especially useful when taking user input; if the user accidentally left a space you clean it up. " apple ".trim() gives "apple".

If you only want to clean one side, there are trimLeft and trimRight as well. trim does not modify the original string; it returns a new one. So do not forget to assign the result to a variable.

padLeft and padRight

To pad a string to a given length use padLeft and padRight. They fill the missing characters with a character you choose. "7".padLeft(3, "0") gives "007". Ideal for showing numbers at a fixed width.

If no padding character is given, space is used by default. padRight does the same from the right: "ad".padRight(5, "_") gives "ad___". Neither adds anything if the string already meets or exceeds the target length; they never shorten it.

Practice Your turn: trim and padLeft

First trim the string " 7 ", then pad it to three characters on the left with padLeft(3, "0"). Print the result with print.

Starter code

main.dart
void main() {
  // First trim the spaces
  // Then padLeft(3, "0") and print
}

Sample solution

main.dart
void main() {
  final result = "  7  ".trim().padLeft(3, "0");
  print(result);
}

Expected output

007

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does " apple ".trim() return?

main.dart
final x = "  apple  ".trim();
  • "apple "
  • "apple"
  • " apple" Correct answer
  • " apple "

Explanation: trim cuts spaces from both sides.

2 The trim call

Question
final clean = "  apple  ".____();
Answer
final clean = "  apple  ".trim();

Explanation: Write trim; it cleans spaces.

3 Match trim and pad

Term Meaning
trim cuts spaces on both sides
trimLeft cuts spaces on the left
padLeft pads on the left
padRight pads on the right

All lessons in Beginner