trim and pad
- Dart course
- Beginner
- Lesson 90/116
- 5 min
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
void main() {
// First trim the spaces
// Then padLeft(3, "0") and print
}Sample solution
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?
final x = " apple ".trim();- "apple "
- "apple"
- " apple" Correct answer
- " apple "
Explanation: trim cuts spaces from both sides.
2 The trim call
final clean = " apple ".____();
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 |