Dart tutorial : string (explanation with 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 :

main(){
  var firstString = "This string is inside double quotes";
  var secondString = 'This string is inside single quotes';

  print(firstString);
  print(secondString);
}

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 :

main(){
  var firstString = """This string is 
  a
  multiline string""";
  var secondString = '''This string is 
  also a
  multiline string''';

  print(firstString);
  print(secondString);
}

It will print the following output :

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

main(){
  var rawString = r"This is a raw string";

  print(rawString);
}

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 :

main(){
  var firstString = "Hello ";
  var secondString = "World !!";

  print(firstString + secondString);
}

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

main(){
  var string = "We are"
  ' concatenating'
  """ Multiple
  Strings""";


  print(string);
}

Output :

We are concatenating Multiple
  Strings

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 :

main(){
  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.