Menu
CoddyTech

Unicode and Character Indices

Lesson 23 of 48 in Coddy's Swift for C++ Developers course.

C++ std::string is a sequence of char elements and does not automatically decode UTF-8 or segment user-perceived characters. These explicit UTF-8 bytes contain seven bytes, and byte-sequence equality does not normalize canonically equivalent accents. Swift String.count counts Character values representing extended grapheme clusters; its UTF-16 view has a different count. The target therefore reports two Characters, four UTF-16 units and the second Character emoji. A Swift String.Index must refer to a valid position in the string. Counting bytes, scalars or UTF-16 units cannot generally substitute for grapheme segmentation, and normalization answers a separate equality question.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>

int main() {
std::string text = "e\xCC\x81\xF0\x9F\x98\x80";
    std::cout << text.size() << '\n';
    std::cout << std::boolalpha << (std::string("\xC3\xA9") == "e\xCC\x81") << '\n';
}

Swift

Complete program file: main.swift.

let text = "é😀"
print(text.count)
print(text.utf16.count)
let next = text.index(after: text.startIndex)
print(text[next])
challenge icon

Challenge

Easy

Implement uniqueCharacters(_:) using Swift Character equality: count distinct extended grapheme clusters. Input is one line of at most 50 Characters without line breaks. It may include composed accents or emoji. Output the count. Canonically equivalent Characters compare equal.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return uniqueCharacters("🇨🇦🇨🇦x") == 2 && uniqueCharacters("éé") == 1 && uniqueCharacters("") == 0
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for C++ Developers

Practice on your own: Swift playground