
Think together · Start with a story
The robot receives the secret code CAT. It is not only a word; it is also an ordered sequence of characters.
Break down the process
- Index 0C
- Index 1A
- Index 2T
A string represents a sequence of characters. The order matters: changing the order changes the text.
01Is a string just “some text”?
A string is an ordered sequence of character data. A program can store it, inspect it, and process its elements.
02Which kind of string is commonly used in C++?
Modern C++ commonly uses std::string from the standard library.
#include <string>
std::string greeting = "Hello";
It is convenient for storing and working with a string of characters.
03How is a string related to a char array?
A C-style string is commonly stored in a character array and ends with a special null character, \0.
char text[] = "Hello";
It actually contains:
std::string is a standard-library class, so do not simply say it “is a char array.”
04What does std::string length mean?
std::string s = "Hello";
std::cout << s.size();
The result is 5.
For ordinary ASCII English text, one char is usually one byte, so this also looks like “5 characters.”
05Does one Chinese character count as one char?
Usually not in UTF-8.
std::string s = "你";
In common UTF-8 environments, s.size() usually returns 3 because this character uses 3 UTF-8 bytes.
06What operations can you do with strings?
Concatenate
a + b
Get length
s.size()
Access
s[i]
Search
s.find(...)
07What is an empty string?
std::string s = "";
It is a valid string with a length of 0.
An “empty string” is not the same as “no string object was created.”
What you have learned
- A string is an ordered sequence of character data.
- Modern C++ commonly uses
std::string. - A C-style string and
std::stringare not the same thing. size()counts char units / bytes; it is not guaranteed to equal the number of Unicode characters people see.- Chinese text in UTF-8 usually uses multiple char bytes.
Next: How Do You Traverse and Process a String?
Your turn to try
If CAT has a size of 3, what is the index of its last character?
Ready? Open to see the explanation
2. The length is the number of elements; the last index is one less than the length.