String Functions in Dart

The standard library’s String class provides many useful string-related functions. Here are some examples to give you a sense of the available methods.

void main() {
  // We define a simple print function for brevity
  void p(String label, dynamic value) {
    print('$label $value');
  }

  // Here's a sample of the methods available for String objects.
  // In Dart, these are methods on the String object itself,
  // rather than functions in a separate package.

  p('Contains:  ', 'test'.contains('es'));
  p('Count:     ', 'test'.split('t').length - 1);
  p('HasPrefix: ', 'test'.startsWith('te'));
  p('HasSuffix: ', 'test'.endsWith('st'));
  p('Index:     ', 'test'.indexOf('e'));
  p('Join:      ', ['a', 'b'].join('-'));
  p('Repeat:    ', 'a' * 5);
  p('Replace:   ', 'foo'.replaceAll('o', '0'));
  p('Replace:   ', 'foo'.replaceFirst('o', '0'));
  p('Split:     ', 'a-b-c-d-e'.split('-'));
  p('ToLower:   ', 'TEST'.toLowerCase());
  p('ToUpper:   ', 'test'.toUpperCase());
}

You can find more methods in the String class documentation.

To run the program, save it as string_functions.dart and use the dart command:

$ dart string_functions.dart
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      [a, b, c, d, e]
ToLower:    test
ToUpper:    TEST

Note that Dart’s string manipulation methods are slightly different from those in other languages:

  1. The count functionality is achieved by splitting the string and counting the resulting parts.
  2. HasPrefix and HasSuffix are replaced with startsWith and endsWith respectively.
  3. Replace with a count is not directly available, so we use replaceAll and replaceFirst instead.
  4. String repetition is done using the * operator instead of a repeat method.

These methods provide a powerful set of tools for manipulating strings in Dart.