In this chapter, we will learn about String data types and the properties and methods of Strings that are available in dart.
Dart Strings
String refers to the collection of characters. For example,
String name = ‘Phil’;
In dart, strings are enclosed in either single quotes or double quotes. The keyword String is used to represent string value.
For example,
void main() {
String name1 = ‘Phil’;
String name2 = “Lauren”;
print(name1);
print(name2);
}
Output
Phil
Lauren
Accessing Variables
We can use the quotes to access the variables and the strings using the dollar sign $ followed by the curly braces { }. For example,
void main() {
int age = 22;
String name = "Sam";
print("${name} is ${age} years old.");
}
Output
Sam is 22 years old.
String Properties
Dart also provides various properties and methods that make the life of a programmer easier.
Some of the String properties are:
Property | Description |
length | Returns the length of the string |
isEmpty | Returns true if the string is empty |
codeUnits | Returns an unmodified list of the UTF-16 code units of this string |
String Properties Examples
void main() {
String name1 = "";
String name2 = "Phil";
print(name1.isEmpty);
print(name2.length);
print(name2.codeUnits);
}
Output
true
4
[80, 104, 105, 108]
String Methods
Some of the useful String methods are:
Methods | Description |
toUpperCase() | Converts all character to uppercase |
toLowerCase() | Converts all character to lowercase |
compareTo() | Compares one string from another |
trim() | Removes all whitespace from leading and trailing spaces. |
split() | Splits the string at matches of the specified delimiter and returns the list of the substring. |
toString() | Returns the string representation of the given object |
subString() | Returns the substring from start index, inclusive to end index |
codeUnitAt() | Returns the 16-bits code unit at the given index |
replaceAll() | Replaces all substring that matches the specified pattern with a given string |
String Method Examples
void main() {
String name1 = "Phil";
String name2 = " Hello World! ";
print(name1.toUpperCase());
print(name1.toLowerCase());
print(name1.compareTo('Phil'));
print(name2.trim());
print(name1.substring(2,4));
print(name1.replaceAll('il','oebe'));
print(name1.split(''));
}
Output
PHIL
phil
0
Hello World!
il
Phoebe
[P, h, i, l]
In next chapter, We will learn about Dart Numbers.