In this tutorial you will learn about the Dart String and its application with practical example.
Dart String
A string variable is used to hold series or sequence of characters – letters, numbers, and special characters. In Dart, string can be represented either using single quotes or double quotes. In Dart, strings can be declared using the String keyword.
1 |
Var msg="Hello World!"; |
Printing String
In Dart, the print()
function is used to print the formatted message to the screen, or other standard output device. The message can be a string, any other object, or any expression, the object and expression will be converted into a string before written to the screen.
Example:-
1 |
print("Hello World") |
Output:-
1 |
Hello World |
String Concatenation
In Dart, strings can be concatenated simply using the plus (‘+’) operator or the +=
assignment operator.
Example:-
1 2 3 4 5 6 |
void main() { var str1 = "Welcome to "; var str2 = "W3Adda"; var str3 = str1 + str2; print(str3); } |
Output:-
1 |
Welcome to W3Adda |
String Interpolation
String interpolation is the process of evaluating a string containing placeholders, variables and interpolated expressions. When an interpolated string is evaluated the placeholders, variables and expressions are replaced with their corresponding values. In Dart, ${expression}
is used for string interpolation.
Example:-
1 2 3 4 5 6 |
void main() { var name = "John"; var age = 25; print("I am ${name} I am ${age} years old"); } |
Output:-
1 2 |
Hello World I am John I am 25 years old |
String Properties
Below is a list of properties supported by Dart Strings.
Property | Description |
---|---|
codeUnits |
Returns an unmodifiable list of the UTF-16 code units of this string. |
isEmpty |
Returns true if this string is empty. |
Length |
Returns the length of the string including space, tab and newline characters. |
String Methods
Below is a list of commonly used methods supported by Dart Strings.
Method | Description |
---|---|
toLowerCase() |
Converts all characters in this string to lower case. |
toUpperCase() |
Converts all characters in this string to upper case. |
trim() |
Returns the string without any leading and trailing whitespace. |
compareTo() |
Compares this object to another. |
replaceAll() |
Replaces all substrings that match the specified pattern with a given value. |
split() |
Splits the string at matches of the specified delimiter and returns a list of substrings. |
substring() |
Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive. |
toString() |
Returns a string representation of this object. |
codeUnitAt() |
Returns the 16-bit UTF-16 code unit at the given index. |