Dart String codeUnitAt()
Syntax & Examples

Syntax of String.codeUnitAt()

The syntax of String.codeUnitAt() method is:

 int codeUnitAt(int index) 

This codeUnitAt() method of String returns the 16-bit UTF-16 code unit at the given index.

Parameters

ParameterOptional/RequiredDescription
indexrequiredthe index at which to retrieve the UTF-16 code unit

Return Type

String.codeUnitAt() returns value of type int.



✐ Examples

1 Get code unit at index 1

In this example,

  1. We create a string str with the value 'Hello'.
  2. We then use the codeUnitAt() method with index 1 to retrieve the UTF-16 code unit at that index.
  3. We print the code unit to standard output.

Dart Program

void main() {
  String str = 'Hello';
  int codeUnit = str.codeUnitAt(1);
  print('Code unit at index 1: $codeUnit');
}

Output

Code unit at index 1: 101

2 Get code unit at index 3

In this example,

  1. We create a string str with the value '12345'.
  2. We then use the codeUnitAt() method with index 3 to retrieve the UTF-16 code unit at that index.
  3. We print the code unit to standard output.

Dart Program

void main() {
  String str = '12345';
  int codeUnit = str.codeUnitAt(3);
  print('Code unit at index 3: $codeUnit');
}

Output

Code unit at index 3: 52

3 Get code unit at index 0

In this example,

  1. We create a string str with the value 'abc'.
  2. We then use the codeUnitAt() method with index 0 to retrieve the UTF-16 code unit at that index.
  3. We print the code unit to standard output.

Dart Program

void main() {
  String str = 'abc';
  int codeUnit = str.codeUnitAt(0);
  print('Code unit at index 0: $codeUnit');
}

Output

Code unit at index 0: 97

Summary

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