In practice, the string series in c ++ -- initialization, deletion, and Case sensitivity of string (construct erase upper-lower)
The string has an iterator design pattern, and I have not yet realized the benefits brought by the iterator. Many times I can use methods similar to array indexes to complete the task.
Scenario 1: Delete all uppercase letters of a string
Here the erase method is used:
#include
#include
#include
using namespace std; int main() { string str = "This IS A trick"; for(string::iterator iter = str.begin(); iter != str.end();++iter){ if(isupper(*iter)){ str.erase(iter); --iter; } } for(string::iterator iter = str.begin(); iter != str.end();++iter) cout<<*iter<<" "; return 0; }
The above code will be wrong, because the previous blog "unescaped pitfalls-after erase is used by vector, the iterator becomes a wild Pointer" said, that is, the position pointed by the iterator after erase.
Scenario 2: initialize a string
I have discussed the initialization of string in my blog:
#include
#include
using namespace std;int main(){ string s = "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz" + 'A'; int t = 'A'; string s1 = "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz" + t; cout << t << endl; cout << s << endl; cout << s1 << endl; return 0;}
The output result is unexpected:
65
Tuvwxyz
Tuvwxyz
Note that the difference between character and string should be clarified. Do not write double quotation marks as single quotation marks.
Cause:
Convert char type to integer type
Const char * pointer offset pointer passed to the string Constructor
Scenario 3: uppercase/lowercase letters in string
The general for loop will not be written, and a seldom used one will be written directly:
# Include
# Include using namespace std; int main () {string str = "heLLo"; // It may not contain
Transform (str. begin (), str. end (), str. begin (), toupper); cout <
Cout <
Note that cout cannot directly output a string.
This leads to an important topic. It does not contain the string header file. Can it be used as a string object? Can it be used as a string object or a string object?
I guess this is why the standard library is constantly updated, and to be compatible with earlier versions