C++ std::string::size (UTF-8)
Measure the UTF-8 byte length of text that will be written to a file or sent in a message.
A simple example
std::string::size (UTF-8)
- Start with "é"
- Do this Encode in UTF-8
- Result 2 bytes
#include <iostream>
#include <string>
int main() {
const std::string value = "é";
std::cout << (value.size()) << "\n";
return 0;
}
2
Syntax
value.size()
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonMeasure a café line on a receipt
A small device accepts an encoded label with a byte limit. Work with its actual encoding to determine what will be transmitted when the text contains more than plain ASCII.
#include <iostream>
#include <string>
int main() {
const std::string value = "café";
std::cout << (value.size()) << "\n";
return 0;
}
5
The letter é requires two UTF-8 bytes.
Budget space for a reaction icon
A messaging service budgets storage for reaction icons. Determine how many bytes one emoji occupies in the chosen encoding before reserving space in an outgoing message.
#include <iostream>
#include <string>
int main() {
const std::string value = "😀";
std::cout << (value.size()) << "\n";
return 0;
}
4
The emoji occupies four UTF-8 bytes.
Count the bytes on a café tag
The word café ends in a precomposed accented character. Trace a UTF-8 round trip. How many bytes carry this label before it is decoded back to the original text?
What to watch for
Always identify the encoding. String length and encoded byte length can differ.