string
Basic usage of a string
in the document
general use
2. Iterator
1. Basic use
A very powerful operator [ ] is overloaded in string
This operator is essentially dereference, the operator that arrays use to access data. So we can operate on each character with this operator. Add a little knowledge: string is a class, and there are many member functions in the class. These member functions will be discussed below. Here, a size is first used to represent the length of the string.
access each character
iterator
2. Syntactic sugar
The principle here is to copy each character of s2 into ch, and auto will automatically deduce the type of ch. Because ch is a copied value, changing ch below will not change s2. If we need to change, we have to use &
This looks like a range for, but in fact the bottom layer is still an iterator.
3. Reverse iterator
4. const iterator
This is actually a problem of privilege amplification, const objects should also call const iterators.
**
To add: Why can const be modified, but it can be ++? Knowledge because const actually modifies *it, not it.
3. Capacity
We can see that it has a capacity function, which is the capacity. If the capacity is not enough, it will automatically expand the capacity. Different compilers have different expansion sizes. In vs2019, the capacity is expanded by 1.5 times each time. Obviously, the cost of such expansion is very high, and it is easy to run out of space, so it provides a reserve function.
There is also a resize function above, the difference between resize and reserve is: resize is open space + initialization (default is \0), reserve is simply open space.
4. Insertion and deletion
insert
delete
Use insert and erase with caution. Insertion and deletion are very inefficient and should be avoided if possible.
5. A sample question: Parsing protocol
find function
substr function
6. Read spaces
The string will automatically stop when it encounters a space when using cin to read. Using this function, you can read the space and control it freely.
7. Some other functions
string to integer
String to double
Others to string