Dart/Flutter String Functions & Operators tutorial with examples

A Dart string is a sequence of UTF-16 (16-bit Unicode Transformation Format) code units. It makes Dart more powerful to build our mobile and web applications in any language. In this tutorial, we’re gonna look at many Dart String Functions & Operators that are helpful. You will know:

  • Ways to create some kind of Strings in Dart/Flutter
  • Methods get data from a String in Dart/Flutter
  • Basic methods to validate data inside a String in Dart/Flutter
  • How to transfrom, split, join, trim Strings in Dart/Flutter
  • Some kind of methods to replace substring in a String in Dart/Flutter

Related Posts:
Dart/Flutter Constructors tutorial with examples
Dart/Flutter Future Tutorial with Examples
Dart/Flutter List Tutorial with Examples
Dart/Flutter Map Tutorial with Examples
Dart/Flutter – Sort list of Objects


How to create Strings in Dart/Flutter

Create normal Strings

To create a String, we can use single or double quotes:

String s1 = 'bezkoder.com - Mobile code examples';
String s2 = "bezkoder.com - Mobile App Development tutorials";

String s3 = 'It\'s not easy to become a developer, but worthy!';
String s4 = "It's not easy to become a developer, but worthy!";
// It's not easy to become a developer, but worthy!

Create raw Strings

For raw string, we’re gonna use r before quotation mark of a string:

String raws1 = r'bezkoder.com\nMobile App Development tutorials';
print(raws1);
// bezkoder.com\nMobile App Development tutorials

String raws2 = r"It\'s not easy to become a developer, but worthy!";
print(raws2);
// It\'s not easy to become a developer, but worthy!

Create multi-lines Strings

We’re gonna use a triple quote to create a multi-lines Strings:

String s1 = '''bezkoder.com
Mobile Code examples''';
print(s1);
/*
bezkoder.com
Mobile Code examples
*/

String s2 = """bezkoder.com
App Development tutorials""";
print(s2);
/*
bezkoder.com
App Development tutorials
*/

Create Strings with UTF-32 units

We’ve known that a Dart string is a sequence of UTF-16 code units. So to create Strings with UTF-32 units, we need to use specific syntax:
\uXXXX for 4-digit hexadecimal value
\u{XX} or \u{XXXXX} (hexadecimal value in curly brackets) for less or more than 4-digits.

String u1 = 'Unicode emoticon characters: \u{1f603} \u{1f604} \u{1f605} \u{1f606} \u{1f607}';
print(u1);
// Unicode 5-digit: ? ? ? ? ?

String u2 = 'Miscellaneous symbols: \u{266A} \u{266B} \u{266C} \u{266D} \u{266E} \u{266F}';
print(u2);
// Miscellaneous symbols: ♪ ♫ ♬ ♭ ♮ ♯

String u3 = 'Greek characters: \u{3B1} \u{3B2} \u{3B3} \u{3B4} \u{3B5}';
print(u3);
// Greek characters: α β γ δ ε

Dart/Flutter Get characters by indexes

Get one character by its index

Now we think of a Dart String as a list with each character as an item:

String str = 'bezkoder.com - Mobile code examples';
str[0]; // b
str[2]; // z

In the code above, we use Dart String operator [].

Get substring in Dart/Flutter

To get substring from a Dart String, we use substring() method:

String str = 'bezkoder.com';
str.substring(0,8); // bezkoder
str.substring(2,8); // zkoder
str.substring(3);   // koder.com

This is the signature of substring() method that returns a String:

String substring(int startIndex, [int endIndex]);

startIndex: index of character to start with. Beginning index is 0.
endIndex (optional): index of ending character + 1. If it is not set, the result will be a subtring starting from startIndex to the end of the string.

For example, we want ‘r’ is the ending. In ‘bezkoder.com’, the index of ‘r’ is 7. So we need to set endIndex by 8.

Dart/Flutter Get position of character/substring in a String

For the first match

We can do this by using indexOf() method:

String s = 'bezkoder.com';
s.indexOf('e');           // 1
s.indexOf('er');          // 6
s.indexOf(RegExp(r'e.')); // 1
s.indexOf('code');        // -1

indexOf() will returns -1 if there is no match.

For the last match

We can do this by using lastIndexOf() method:

String s = 'bezkoder.com';
s.lastIndexOf('e');           // 6
s.lastIndexOf(RegExp(r'e.')); // 6
s.lastIndexOf('code');        // -1

lastIndexOf() will returns -1 if there is no match.

Dart/Flutter transform String functions

Upper and Lower String

toUpperCase() and toLowerCase() methods return a new string (not change the original string) with all letters have been converted to uppercase or lowercase format:

String str = 'bezkoder';
String upperStr = str.toUpperCase();
print(upperStr); // BEZKODER
print(str);      // bezkoder

String lowerStr = upperStr.toLowerCase();
print(lowerStr); // bezkoder
print(upperStr); // BEZKODER

Dart/Flutter Capitalize first letter

We can convert first letter of a string to uppercase letter and lowercase others using intl library toBeginningOfSentenceCase() method:

import 'package:intl/intl.dart';

main() {
  String sentence = toBeginningOfSentenceCase('bezkoder');
  print(sentence); // Bezkoder
}

Dart/Flutter Validate String

Check Empty String

We use Dart String properties isEmpty or isNotEmpty to know if a String is empty or not:

String emp = '';
emp.isEmpty;    // true
emp.isNotEmpty; // false

Check if String contains a substring or not

We use contains() method with signature as below:

bool contains(Pattern substring, [int startIndex = 0]);

substring could be a String or a RegExp object.
startIndex (optional): the index that from it, the method matches substring.

String s = 'bezkoder';
s.contains('k');                 // true
s.contains(RegExp(r'[a-c]'));    // true

s.contains('z', 3);              // false
s.contains(RegExp(r'[a-c]'), 1); // false
s.contains(RegExp(r'[a-d]'), 1); // true

Check if String starts/ends with character/string

We can do this with endsWith() method:

String s = 'bezkoder';

s.startsWith('b');   // true
s.startsWith('z');   // false
s.startsWith('bez'); // true

s.endsWith('r');     // true
s.endsWith('z');     // false
s.endsWith('koder'); // true

Dart/Flutter String concatenation

Join/Concatenate Strings

We have 3 ways to concatenate two Dart Strings:

  • use interpolation
  • separate strings in one statement
  • use Dart String operator +
String a = 'bezkoder';
String b = '.com';

String s1 = '$a$b';    // interpolation
String s2 = '$a' '$b'; // separated in one statement
String s3 = a + b;     // operator
/* bezkoder.com */

Concatenate a String with itself

Using Dart String operator *, we can multiply a String by a number of times:

String s = '=bezkoder';
print(s*3);
// =bezkoder=bezkoder=bezkoder

Dart/Flutter Split String

The split() method splits the string at matches of pattern and returns a list of substrings between the matches:

List split(Pattern pattern);

The pattern input param could be a String or a RegExp object. For example:

String s1 = 'bezkoder.earth.com';
s1.split('.');
// [bezkoder, earth, com]

String s2 = 'bezkoder2019.com';
s2.split(RegExp(r'[0-9]+'));
// [bezkoder, .com]

String s3 = 'bezkoder';
s3.split('');
// [b, e, z, k, o, d, e, r]

Split String, convert parts, then Join Strings

Dart provides splitMapJoin() method that can do 3 things in one statement:

String splitMapJoin(
    Pattern pattern,
    {String onMatch(Match match), String onNonMatch(String nonMatch)}
);

pattern could be a String or a RegExp object.
onMatch (optional): converts each match to a string.
onNonMatch (optional): converts each non-matched part to a string.

String result = 'bezkoder2019.com'.splitMapJoin(
  RegExp(r'[0-9]+'),
  onMatch: (m) => '_${m.group(0)}_',
  onNonMatch: (n) => '[${n}]');

print(result);
// [bezkoder]_2019_[.com]

result = 'bezkoder2019.com'.splitMapJoin(
  RegExp(r'[0-9]+'),
  onNonMatch: (n) => '[${n}]');

print(result);
// [bezkoder]2019[.com]

result = 'bezkoder2019.com'.splitMapJoin(
  RegExp(r'[0-9]+'),
  onMatch: (m) => '_${m.group(0)}_');

print(result);
// bezkoder_2019_.com

Dart/Flutter Justify text

padLeft() method returns a right-justified String with given minimum width. If width is smaller than or equal to length of the String, no padding is added.
padRight() method returns a left-justified String with given minimum width. If width is smaller than or equal to length of the String, no padding is added.

String s = 'bezkoder';

s.padLeft(10);       // '  bezkoder'
s.padLeft(10, '=');  // '==bezkoder'

s.padRight(10);      // 'bezkoder  '
s.padRight(10, '='); // 'bezkoder=='

Dart/Flutter Trim String

trimLeft() returns new String without whitespace characters from the left.
trimRight() is from the right.
trim() returns a new String without any whitespace characters at the beginning or end.

String s = '\tbezkoder.com ';
s.trimLeft();  // 'bezkoder.com '
s.trimRight(); // '\tbezkoder.com'
s.trim();      // 'bezkoder.com'

Dart/Flutter String Replace Methods

For the First match

String replaceFirst(Pattern from, String to, [int startIndex = 0]);
String replaceFirstMapped(Pattern from, String replace(Match match),[int startIndex = 0]);

replaceFirst() method returns a new String that replaces the first match of from with to, starts from startIndex.
replaceFirstMapped() returns a new String in which, the first match of from is replaced by the result of replace(match) function.

String s = 'bezkoder.com';
s.replaceFirst('e', 'E');    // bEzkoder.com
s.replaceFirst('e', 'E', 3); // bezkodEr.com
s.replaceFirst(RegExp(r'koder'), 'programmer'); // bezprogrammer.com

s.replaceFirstMapped('e', (m) => '[${m.group(0)}]');    // b[e]zkoder.com
s.replaceFirstMapped('e', (m) => '[${m.group(0)}]', 3); // bezkod[e]r.com 

For All matches

replaceAll() method returns a new String that replaces all matches with another String.
replaceAllMapped() method returns a new String in which, all matches are replaced by the result of replace(match) function.

String s = 'bezkoder.com';
s.replaceAll('e', '[e]');
// b[e]zkod[e]r.com

s.replaceAllMapped(RegExp(r'e.'),
    (m) => m.group(0).contains('z') ? m.group(0) : '[' + m.group(0) + ']');
// bezkod[er].com

You can see that replaceAllMapped() method is useful in case we want to return new content depending on the match.

In range

If we want to replace a range of a String with another String without caring about what it is, we can use replaceRange() method:

String replaceRange(int start, int end, String replacement);

The method will replace the substring from start index to end index with replacement.

String s = 'bezkoder.com';
s.replaceRange(2, 4, 'zzzzzzzzz');
// bezzzzzzzzzoder.com

Conclusion

We have learned many things of Dart String, from create, get, validate to transfrom, split, join, trim String, replace substring… I hope you have a good view and idea about how to work with Dart String Functions & Operators.

Happy learning!

Further reading

Dart/Flutter Constructors tutorial with examples
Dart/Flutter Future Tutorial with Examples
Dart/Flutter List Tutorial with Examples
Dart/Flutter Map Tutorial with Examples
Dart/Flutter – Sort list of Objects

3 thoughts to “Dart/Flutter String Functions & Operators tutorial with examples”

  1. Pretty nice post. I must say that I have really enjoyed this Dart tutorial.
    Hope you write again soon!

Comments are closed to reduce spam. If you have any question, please send me an email.