Dart tutorial : string (explanation with examples)

Published by admin on

Dart string explanation & examples

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 :

  var firstString = "This string is inside double quotes";
  var secondString = 'This string is inside single quotes';


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 :

  var firstString = """This string is 
  multiline string""";
  var secondString = '''This string is 
  also a
  multiline string''';


It will print the following output :

This string is
  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 :

  var rawString = r"This is a raw string";


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 :

  var firstString = "Hello ";
  var secondString = "World !!";

  print(firstString + secondString);

It will print Hello World !! as output. Similarly,

  var string = "We are"
  ' concatenating'
  """ Multiple


Output :

We are concatenating Multiple

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 :

  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 :

1. isEmpty : This is a read-only property. It returns true if the string is empty, false otherwise.
2. isNotEmpty : Returns true if this string is not empty.
3. length : It returns the number of UTF-16 code units in this string.
4. hashCode : Returns a hash code derived from the code units of the string.
5. toLowerCase(): Converts all characters of the string to lower case.
6. toUpperCase(): Converts all characters of the string to upper case.
7. trim(): trim the string, i.e. removes all leading and trailing spaces.
8. replaceAll(Pattern from, String replace): Replace all substring that matches ‘from’ with ‘replace’ and returns the final string.
9. replaceRange(int start, int end, String replacement): Replace the substring from ‘start’ to ‘end’ with substring ‘replacement’.
10. toString(): Returns the string representation of this object.

Categories: dart


Leave a Reply

Your email address will not be published. Required fields are marked *