Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
runes
strings
unicode
code units

Dart Runes

Anusheh Zohair Mustafeez

In Dart, strings are represented as sequences of Unicode UTF-16 code units. The Unicode format maps a unique numeric character to each letter, digit, and symbol. The code below shows Unicode equivalents of some characters.

import 'dart:convert';
void main() {
    //Unicode equivalent of uppercase M
    var uppercaseM = '\u{004d}';
    print(uppercaseM);

    //Unicode equivalent of the digit 7
    var seven = '\u{0037}';
    print(seven);

    //Unicode equivalent of the the dollar sign
    var dollarSign = '\u{0024}';
    print(dollarSign);

    //Unicode equivalent of the thumbs-up emoji
    var thumbsUp = '\u{1f44d}';
    print(thumbsUp);    
}

A rune is an integer that represents a Unicode code point. The dart:core library allows runes to be accessed from Dart strings. There are three main methods used for this purpose:

  1. String.codeUnitAt(int index)
    This function takes in the index of a code unit in a string and returns the unit in 16-bit UTF-16 (decimal) format.
import 'dart:convert';
void main() {
    String string = 'Educative';

    //UTF-16 code unit for 'd' at second index of string
    print(string.codeUnitAt(1));

    //UTF-16 code unit for 't' at sixth index of string
    print(string.codeUnitAt(5));
}
  1. String.codeUnits
    This property outputs an unmodifiable list of all the corresponding UTF-16 code units of the string.
import 'dart:convert';
void main() {
    String string = 'Educative';

    //UTF-16 code unit list for the string above
    print(string.codeUnits);
}
  1. String.runes
    This enables iteration through code units.
import 'dart:convert';
void main() {
    String string = 'Educative';

    //Iterating over Unicode code-points of the string above
    string.runes.forEach((int rune) { 
      var char=new String.fromCharCode(rune); 
      print(char); 
   });
}

RELATED TAGS

dart
runes
strings
unicode
code units

CONTRIBUTOR

Anusheh Zohair Mustafeez
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring