An introduction to dart string with examples

Introduction :

The string is a sequence of characters. In dart, a string is consists of a sequence of UTF 16 code units. Each character in dart is consists of multiple code points. Each code point again consists of one or two code units. Following are the types of string supported in dart :

String types :

A string can be of a single line or multi-line. Both single and double quotes are used to represent a string.

Single and double quotes are used to represent one single line string and triple quotes are used to represent one multi-line string. We can also add one double quotes string in a single quote string or a single quote string in a double quotes string.

For example :

void main() {
  String firstString = "Hello World !!";
  String secondString = 'Hello World !!';
  String thirdString = "Hello 'Hello' World !!";
  String fourthString = 'Hello "Hello" World !!';
  String fifthString = """Hello ----
  ----- World
  !!""";

  String sixthString = '''Hello ^^^^
  ^^^^ World !!
  ^^''';

  print(firstString);
  print(secondString);
  print(thirdString);
  print(fourthString);
  print(fifthString);
  print(sixthString);
}

It will print :

Hello World !!
Hello World !!Hello 'Hello' World !!
Hello "Hello" World !!
Hello ----
  ----- World
  !!
Hello ^^^^
  ^^^^ World !!
  ^^

In this example, all are different types of strings that we have mentioned before.

dart string

Strings are immutable :

Strings are immutable in dart. You can’t change them. If you want to change anything in a string, you need to create one new string with the changes.

Concatenate strings :

We can use the plus operator (+) to concatenate two strings. It returns one new strings. We can add any number of strings using the + operator.

For example :

void main() {
 String message = "Hello" +" "+ 'World'+"!!!";

 print(message);
}

It will print :

Hello World!!!

We can also use * to concatenate a string for n number of times with itself. For example :

void main() {
 String message = "Hello";
 print(message*3);
}

It will print :

HelloHelloHello

Expressions within a string :

${} is used to add expression in a string. The curly braces can be removed for identifiers. For example :

void main() {
 String message = "Hello";

 print("Message received : ${message},length ${message.length}");
}

It will print :

Message received : Hello,length 5

These are the basics of dart string. We will publish a few more articles on string with a more advanced concept. Go through the code and drop one comment below if you have any queries.