String in Dart with examples :
In dart, a string is a sequence of UTF-16 code units. To create one string variable, we can use either single quote or double quote like below :
main(){
var firstString = "This string is inside double quotes";
var secondString = 'This string is inside single quotes';
print(firstString);
print(secondString);
}
If you run the above program, it will print the below output :
This string is inside double quotes
This string is inside single quotes
Multiline string :
For multiline string in dart, we can use three single quotes or double quotes. For example :
main(){
var firstString = """This string is
a
multiline string""";
var secondString = '''This string is
also a
multiline string''';
print(firstString);
print(secondString);
}
It will print the following output :
This string is
a
multiline string
This string is
also a
multiline string
Raw string :
For a raw string, we can use r before a string in Dart. Example :
main(){
var rawString = r"This is a raw string";
print(rawString);
}
Concatenate two strings in Dart :
Concatenation or adding two string is same as Java in Dart. We can use plus (+) operator to concatenate two different strings. We can also use adjacent string literals to concatenate two strings, this is not available in Java. For example :
main(){
var firstString = "Hello ";
var secondString = "World !!";
print(firstString + secondString);
}
It will print Hello World !! as output. Similarly,
main(){
var string = "We are"
' concatenating'
""" Multiple
Strings""";
print(string);
}
Output :
We are concatenating Multiple
Strings
Putting a variable or expression inside a string :
We can include any variable or any expression inside a string using $ prefix symbol in dart. For example :
main(){
int number = 10;
double doubleNumber = 10.23;
var booleanValue = true;
print("$number $doubleNumber $booleanValue");
}
It will print :
10 10.23 true
Few useful String properties and methods :
- isEmpty : This is a read-only property. It returns true if the string is empty, false otherwise.
- isNotEmpty : Returns true if this string is not empty.
- length : It returns the number of UTF-16 code units in this string.
- hashCode : Returns a hash code derived from the code units of the string.
- toLowerCase(): Converts all characters of the string to lower case.
- toUpperCase(): Converts all characters of the string to upper case.
- trim(): trim the string, i.e. removes all leading and trailing spaces.
- replaceAll(Pattern from, String replace): Replace all substring that matches ‘from’ with ‘replace’ and returns the final string.
- replaceRange(int start, int end, String replacement): Replace the substring from ‘start’ to ‘end’ with substring ‘replacement’.
- toString(): Returns the string representation of this object.