Dart String Methods
A string method is a call that does a job on a string. The call gives back a result, and the first string stays as it was.
Capital and small letters
toUpperCase turns every letter into a capital. toLowerCase turns every letter into a small letter.
void main() {
print('dart'.toUpperCase());
print('DART'.toLowerCase());
}Finding text inside a string
contains tells whether a piece of text sits inside a string. startsWith tells whether a string begins with a piece of text.
void main() {
print('dartboard'.contains('art'));
print('dartboard'.contains('xyz'));
print('dartboard'.startsWith('dart'));
}Swapping pieces of text
replaceAll swaps every copy it finds. Both copies of cat turn into dog.
void main() {
print('one cat, two cats'.replaceAll('cat', 'dog'));
}Trimming spaces from the ends
The padded string holds six characters, counting its spaces. After trim, only the two letters remain.
void main() {
var padded = ' hi ';
print(padded.length);
print(padded.trim().length);
}Copying a slice of a string
substring starts at index 1 and stops before index 3. The copied slice is ar.
void main() {
print('dart'.substring(1, 3));
}Example
void main() {
var word = ' Dart ';
var clean = word.trim();
print(clean);
print(clean.toLowerCase());
print(clean.toUpperCase());
print(clean.contains('art'));
print(clean.substring(0, 2));
print(clean.replaceAll('Dart', 'Code'));
}Key points
- Use toUpperCase() to turn every letter in a string into a capital letter.
- Use toLowerCase() to turn every letter in a string into a small letter.
- contains reports true when a string holds a given piece of text.
- startsWith reports true when a string begins with a given piece of text.
- replaceAll swaps every copy of one piece of text for another piece.
- trim removes spaces from both ends of a string.
- substring(start, stop) copies characters from the start index and stops before the stop index.
In this example, trim first removes the spaces around Dart. The next two prints show the word in small letters and then in capitals. contains finds art inside Dart, and substring copies the first two letters. The last print swaps Dart for Code.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does 'dart'.toUpperCase() give back?