C++ - Strings: Length

Overview

Estimated time: 10โ€“15 minutes

Measure string length using size() and length(). Understand bytes vs characters.

Learning Objectives

  • Use size()/length() to get string length.
  • Understand why UTF-8 multibyte sequences impact character counts.

Prerequisites

Examples

#include <string>
#include <iostream>
int main(){
  std::string s = "hello";
  std::cout << s.size() << "\n"; // 5
  std::string emoji = "\xF0\x9F\x98\x81"; // ๐Ÿ˜ in UTF-8, 4 bytes
  std::cout << emoji.size() << "\n"; // 4 bytes, but 1 glyph
}

Common Pitfalls

  • std::string measures bytes, not Unicode code points or grapheme clusters.