Summary - Strings
- Dart course
- Beginner
- Lesson 35/116
- 5 min
Combine interpolation, length and contains to write a business card.
Summary - Strings
In this group you learned String creation, interpolation, .length, .toUpperCase(), .substring(), .contains() and .indexOf(). Now we will combine them to print a business card.
The card will show the name, the length and the presence of the @ sign. The goal is to use several String tools together in one program. Each piece is small; together they give a meaningful output.
Information with length
On a business card the number of letters in the name can be informative. With name.length we take the character count, assign it to a new variable and print it with interpolation. Example: var len = name.length; and print("Length: $len");.
The same could be done in one line with ${name.length}; but assigning to len lets us reuse the value later. Building the program step by step makes debugging easier.
Practice Print a business card
Declare a String variable name with the value "Alex". Declare a variable len and assign the result of name.length to it. Then print with print("Name: $name, length: $len");. The output on a single line must be Name: Alex, length: 4.
Starter code
// Declare name, assign length to len, print name and lengthSample solution
String name = "Alex";
var len = name.length;
print("Name: $name, length: $len");Expected output
Name: Alex, length: 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the card line
String name = "Alex";
print("Name: ____");
String name = "Alex";
print("Name: $name");
Explanation: $name embeds the name into the string.
2 How do you check if an email has @?
String email = "a@b.com";- email.length("@")
- email.contains("@") Correct answer
- email.substring("@")
- email.toUpperCase("@")
Explanation: contains("@") returns a bool for the presence of @.