Learn/Dart/8. Strings and a small project
Lesson 8 of 8
Sign in

Dart, lesson 8

Strings and a small project

Text is everywhere: names, commands, messages, files. Dart's String type comes with a big toolbox. One rule underlies all of it: strings never change. Every method that seems to modify a string actually returns a new one, so remember to keep the result.

Looking inside a string

Changing and cleaning

split breaks a string into a list, and join (on a list) glues it back together. Splitting on the empty string gives you single characters:

When spacing between words is messy, split on a regular expression that means "one or more whitespace characters": line.trim().split(RegExp(r'\s+')). The r in front makes a raw string, so the backslash reaches RegExp untouched.

Lining things up

Tables and receipts need columns. adds spaces in front until the string is long, which right-aligns numbers. adds them after, which left-aligns labels:

2 exercises to try what you just read.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

padLeft(width)
width
padRight(width)

Building long strings

Joining strings with + in a loop creates a new string every time. For many pieces, a StringBuffer collects them and builds the final string once:

Putting it together

The project below uses almost everything from this course: reading input in a loop, converting text to numbers, arithmetic, a function, a list or map if you like, and string formatting. Plan it before you type: what do you read, what do you keep, what do you print? Writing a small helper function for one receipt line keeps main tidy.

Further reading

  • Built-in types: Strings
  • Core library tour: strings and regular expressions
  • String API

A palindrome reads the same backwards, like Never odd or even. Read one line, keep only its letters and digits, ignore upper/lower case, and print palindrome or not a palindrome. A line with no letters or digits counts as a palindrome.

Input:

Output:

Print a shop receipt. The first line holds n, the number of items. Each of the next n lines holds a name (one word, at most 8 letters), a unit price and a quantity, separated by spaces.

For each item print name xQTY padded on the right to 12 characters, followed by the line total (price times quantity) with two decimals, padded on the left to 8 characters. Then print a line of 20 dashes, and TOTAL laid out the same way with the sum of all line totals.

Input:

Output:

var name = 'ada';
name.toUpperCase();        // result thrown away, name is still 'ada'
name = name.toUpperCase(); // now name is 'ADA'
final word = 'compiler';
print(word.length);           // 8
print(word[0]);               // c (a one-character string)
print(word.substring(0, 4));  // comp (from index 0 up to, not including, 4)
print(word.substring(3));     // piler (from index 3 to the end)
print(word.indexOf('p'));     // 3, or -1 if not found
print(word.contains('pile')); // true
print(word.startsWith('com'));// true
final raw = '  Hello, Dart!  ';
print(raw.trim());                      // 'Hello, Dart!'
print(raw.toLowerCase());               // '  hello, dart!  '
print('a-b-c'.replaceAll('-', '+'));    // 'a+b+c'
print('na' * 3);                        // 'nanana'
final words = 'red green blue'.split(' ');  // [red, green, blue]
final letters = 'stop'.split('');           // [s, t, o, p]
print(letters.reversed.join());             // pots
print('tea'.padRight(8) + '2.50'.padLeft(6));    // 'tea       2.50'
print('cake'.padRight(8) + '12.00'.padLeft(6));  // 'cake     12.00'
final sb = StringBuffer();
for (var i = 1; i <= 3; i++) {
  sb.write('$i ');
}
print(sb.toString().trim()); // 1 2 3
Never odd or even
palindrome
3
apple 0.50 3
bread 2.25 1
milk 1.10 2
apple x3        1.50
bread x1        2.25
milk x2         2.20
--------------------
TOTAL           5.95