Dart String codeUnits
Syntax & Examples

Syntax of String.codeUnits

The syntax of String.codeUnits property is:

 List<int> codeUnits 

This codeUnits property of String returns an unmodifiable list of the UTF-16 code units of this string.

Return Type

String.codeUnits returns value of type List<int>.



✐ Examples

1 Get code units of a string

In this example,

  1. We create a string str1 with the value 'Hello, world!'.
  2. We then access the codeUnits property of str1 to get the UTF-16 code units as a list of integers.
  3. We print the code units to standard output.

Dart Program

void main() {
  String str1 = 'Hello, world!';
  List<int> codeUnits1 = str1.codeUnits;
  print('Code units of str1: $codeUnits1');
}

Output

Code units of str1: [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]

2 Get code units of a string

In this example,

  1. We create a string str2 with the value 'ABCDEF'.
  2. We then access the codeUnits property of str2 to get the UTF-16 code units as a list of integers.
  3. We print the code units to standard output.

Dart Program

void main() {
  String str2 = 'ABCDEF';
  List<int> codeUnits2 = str2.codeUnits;
  print('Code units of str2: $codeUnits2');
}

Output

Code units of str2: [65, 66, 67, 68, 69, 70]

3 Get code units of a string

In this example,

  1. We create a string str3 with the value 'Lorem ipsum'.
  2. We then access the codeUnits property of str3 to get the UTF-16 code units as a list of integers.
  3. We print the code units to standard output.

Dart Program

void main() {
  String str3 = 'Lorem ipsum';
  List<int> codeUnits3 = str3.codeUnits;
  print('Code units of str3: $codeUnits3');
}

Output

Code units of str3: [76, 111, 114, 101, 109, 32, 105, 112, 115, 117, 109]

Summary

In this Dart tutorial, we learned about codeUnits property of String: the syntax and few working examples with output and detailed explanation for each example.