Strings in Dart

Strings in Dart#

About#

In Dart, a string is a sequence of UTF-16 code units. Strings are used to represent text. Dart supports single quotes ('), double quotes ("), triple single quotes ('''), and triple double quotes (""") to define strings.

How Strings Work#

A string can be defined using:

  • Single quotes: 'Hello'
  • Double quotes: "World"
  • Triple quotes for multi-line strings:
    '''
    Multi-line
    String
    '''
    

Strings in Dart are immutable, meaning once created, they cannot be changed. If you need to manipulate strings, Dart provides various string manipulation methods like concatenation, interpolation, and substring.

How to Use Strings#

1. String Concatenation#

You can concatenate strings using the + operator:

String greeting = 'Hello' + ' World'; // Hello World


### String Interpolation
String interpolation allows you to insert variables into strings using ${}:


```dart
String name = 'John';
String message = 'Hello, $name!'; // Hello, John!

Multi-line Strings#

You can use triple quotes for multi-line strings:

String longMessage = '''
This is a multi-line
string in Dart.
''';

Escape Characters#

Escape characters can be used to include special characters within a string:

String text = 'It\'s a beautiful day!';

Example#

void main() {
  String name = 'Alice';
  int age = 25;

  // String interpolation
  String message = 'My name is $name and I am $age years old.';

  // Multi-line string
  String bio = '''
  Hello, my name is $name.
  I love coding in Dart.
  ''';

  // Concatenation
  String greeting = 'Welcome, ' + name + '!';

  print(message);  // Output: My name is Alice and I am 25 years old.
  print(bio);      // Output: Multi-line string with bio
  print(greeting); // Output: Welcome, Alice!
}

In this example, you can see how Dart handles string interpolation, concatenation, and multi-line strings efficiently.