31 December 2020
cpp -- Object-Oriented Thinking(1)
by Jerry Zhang
The string Class
A better way to create a string is to use the string constructor like this:
string s("Welcome to C++");
Append
- 接一个string
string s1("Welcome");
s1.append(" to C++"); // Appends " to C++" to s1
cout << s1 << endl; // s1 now becomes Welcome to C++
- 接一个string从index开始的n个字符
string s2("Welcome");
s2.append(" to C and C++", 0, 5); // Appends " to C" to s2
cout << s2 << endl; // s2 now becomes Welcome to C
- 接一个string的前n个字符
string s3("Welcome");
s3.append(" to C and C++", 5); // Appends " to C" to s3
cout << s3 << endl; // s3 now becomes Welcome to C
- 接n次这个string
string s4("Welcome");
s4.append(4, 'G'); // Appends "GGGG" to s4
cout << s4 << endl; // s4 now becomes WelcomeGGGG
Assign
跟上一个用法类似
at, clear, erase, and empty
at 可以用方括号代替
length, size, capacity, and c_str()
length(), size()是一样的。c_str() 和 data()是一样的
Substring
- substr(index: int, n: int) 从index开始的n个字符
- substr(index: int) 从index开始的后面所有
Searching in a String
用find函数搜索一个字符或者子串,如果找不到,返回的是string::npos
string s1("Welcome to HTML");
cout << s1.find("co") << endl; // Returns 3
cout << s1.find("co", 6) << endl; // Returns string::npos
cout << s1.find('o') << endl; // Returns 4
cout << s1.find('o', 6) << endl; // Returns 9
Inserting and Replacing Strings
- insert(index: int, s: string) 在index的位置插入字符s
string s1("Welcome to HTML");
s1.insert(11, "C++ and ");
cout << s1 << endl; // s1 becomes Welcome to C++ and HTML
- insert(index: int, n: int, ch: char) 在index插入n次字符ch
string s2("AA");
s2.insert(1, 4, 'B');
cout << s2 << endl; // s2 becomes to ABBBBA
- replace(index: int, n: int, s: string) 从index开始的n个字符,用s来替换
string s3("Welcome to HTML");
s3.replace(11, 4, "C++");
cout << s3 << endl; // s3 becomes Welcome to C++
String Operators
等于号其实是把一个string的内容copy到另一个string
string s1 = "ABC";
Instance and Static Members
A static variable is shared by all objects of the class. A static function cannot access instance members of the class.
tags: cpp