substring
- Dart course
- Beginner
- Lesson 33/116
- 5 min
Learn to take parts of a string with substring.
substring
To take a part of a String you use the .substring(start, end) method. start is inclusive, end is exclusive: "DartLang".substring(0, 4) returns "Dart". Indexing is zero-based.
If you omit the second parameter it goes to the end of the String: "DartLang".substring(4) returns "Lang". Negative indices are not supported; keep indices within the String length to avoid errors.
Start and end rules
In substring the start index exists in the string and is included in the result. The end index is excluded; it means "take up to here". "welcome".substring(0, 3) takes the letters w, e, l and returns "wel".
Both parameters must be between 0 and length. start cannot be greater than end; otherwise an error is thrown. Practical tip: the number of characters taken is end - start.
Practice Take the first 4 characters
Declare a String variable word with the value "DartLang". Declare a new variable first and assign the result of word.substring(0, 4) to it. Then print first with print(first);. The output on a single line must be Dart.
Starter code
// Declare word, assign the first 4 chars to first via substring, print itSample solution
String word = "DartLang";
var first = word.substring(0, 4);
print(first);Expected output
Dart
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the call to its meaning
| Term | Meaning |
|---|---|
substring(0, 3) |
First 3 characters |
substring(2) |
From index 2 to end |
substring(0, 1) |
First character |
substring(1, 3) |
Middle part |
2 Write the substring call
String word = "Dart";
print(word____);
String word = "Dart";
print(word.substring(0, 3));
Explanation: .substring(0, 3) takes the first 3 characters.
3 What does "welcome".substring(0, 3) return?
"welcome".substring(0, 3)- "welc"
- "w"
- "lco"
- "wel" Correct answer
Explanation: substring(0, 3) takes indices 0, 1, 2: wel.