Strings in Dart#
In Dart, strings are sequences of UTF-16 code units and are used to represent text. Dart strings are immutable, which means once you create a string, you cannot change its content. Below are detailed examples and explanations of how to work with strings in Dart.
Creating Strings#
Dart provides several ways to define strings:
Single and Double Quotes#
You can create strings with either single or double quotes; there’s no difference in their functionality.
String greeting = 'Hello';
String response = "Hi there";
Multiline Strings#
For strings that span multiple lines, you can use triple quotes with either single or double quotation marks.
String longText = '''
This is a string
that spans multiple
lines.
''';
String verboseText = """
Another example
of a multiline
string.
""";
Raw Strings#
If you want to create a string where the escape sequences are treated as plain text, use a raw string, which is prefixed with ‘r’.
String Operations#
Dart strings offer numerous methods for manipulation and query.
Concatenation#
Strings can be concatenated using the + operator or string interpolation for more readability and efficiency.
String firstName = 'John';
String lastName = 'Doe';
String fullName = firstName + ' ' + lastName;
String interpolatedFullName = '$firstName $lastName';