Characters of a Text
A std::string text isn't a vector, but it's similar to one in many ways: it's a sequence of characters. Each character has an index, counted from 0, and you can read it with square brackets or the method at():
std::string word = "Code";
std::cout << word[0] << std::endl;
std::cout << word.at(1) << std::endl;
std::cout << word[word.size() - 1] << std::endl;This prints:
C
o
eIn C++, a single character has its own data type, char, which you know from the lesson on variables. So you can store a character read from a text in a char variable. You write a char value in single quotes, 'C', and a text in double quotes, "C". std::cout prints a character without quotes:
char firstChar = word[0];
std::cout << firstChar << std::endl;
if (firstChar == 'C') {
std::cout << "Starts with C" << std::endl;
}This prints:
C
Starts with CA common mistake is to compare a character with a text in double quotes: if (word[0] == "C"). Then the program doesn't compile:
main.cpp:7:17: error: comparison between pointer and integer ('value_type' (aka 'char') and 'const char *')The message talks about comparing a pointer with an integer. You'll meet pointers in the lesson on references and pointers. For now, remember: when you see this error with a character, replace the double quotes with single ones.
You get the number of characters with the method size(), just like for a vector. A text also has the method length(), which gives the same number. Spaces and punctuation marks are characters too, so "Hi, Tom!" has 8 characters:
std::string greeting = "Hi, Tom!";
std::cout << greeting.size() << " " << greeting.length() << std::endl;This prints:
8 8An index outside the text works the same way as with a vector: word[10] reads something meaningless, and word.at(10) stops the program with an error.
You can also change a character of a text:
std::string name = "Tim";
name[0] = 'J';
std::cout << name << std::endl;This prints:
JimWatch out for letters with accents, such as é or ü. They take up two bytes in a text, that is, two chars (this is how the UTF-8 encoding stores text). So "café" has a size of 5, not 4, and its last char is only half of the é. You can print such texts without any problem, but write the texts you work with character by character without accents.
Instructions
- 1
Store the first character of the text
namein acharvariable namedfirstChar. You can use square brackets or the methodat(). - 2
On one line, print the first character, the last character and the number of characters of the name, separated by spaces. Find the last character with
size() - 1orlength() - 1. The output should include the lineT a 4. - 3
Below that, write a statement that changes the first character of the name to
'N', and then print the name. The output should include the lineNina.