thumbnail

Strings and raw strings in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

What are Strings in Dart

In Dart programming language, Strings are defined as a sequence of UTF 16 code units.

There are various ways to define a String in Dart.

Various ways to define a String in Dart programming language are demonstrated given below.

Different ways to define a String in Dart

Program:

void main() {
  var string1 = 'string defined using single quotes';
  print(string1);
  var string2 = "string defined using double quotes";
  print(string2);

  var multiLineStringInDart = '''
This is a multi line string.
''';
  print(multiLineStringInDart);

  var multiLineStringType2InDart = """
This is yet another way to define multi line string in Dart.
  """;
  print(multiLineStringType2InDart);
}

Above program produces following output:

string defined using single quotes
string defined using double quotes
This is a multi line string.

This is yet another way to define multi line string in Dart.

Explanation: Above program shows various ways to define a String in Dart.

Defining raw Strings in Dart

What is a raw strings in Dart: In Dart programming language, raw strings are a type of strings where special characters such as \ do not get special treatment.

Raw strings are useful when you want to define a String that has a lot of special characters.

Program:

void main() {
  var rawString =
      r'This is raw string where \ and ${1+2} do not have special meaning.';
  print(rawString);
}

Above program produces following output:

This is raw string where \ and ${1+2} do not have special meaning.

Explanation: Above program demonstrates how raw strings can be defined in Dart.

String interpolation in Dart

Program:

void main() {
  var string1 = 'string1';
  var string2 = 'string2';

  // string interpolation using the + operator
  print(string1 + ' ' + string2);

  // string interpolation using the ${} operator
  print('${string1} ${string2}');

  // string interpolation using dart expressions
  print('1 + 2 = ${1 + 2}');
}

Above program produces following output:

string1 string2
string1 string2
1 + 2 = 3

Explanation: As shown in above program, Strings can be interpolated using the + operator or ${} operator.

Also note that ${} can be used to evaluate Dart expressions.