Jerry's Blog

Recording what I learned everyday

View on GitHub


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 s1("Welcome");
s1.append(" to C++"); // Appends " to C++" to s1
cout << s1 << endl; // s1 now becomes Welcome to C++
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 s3("Welcome");
s3.append(" to C and C++", 5); // Appends " to C" to s3
cout << s3 << endl; // s3 now becomes Welcome to C
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

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

string s1("Welcome to HTML");
s1.insert(11, "C++ and ");
cout << s1 << endl; // s1 becomes Welcome to C++ and HTML
string s2("AA");
s2.insert(1, 4, 'B');
cout << s2 << endl; // s2 becomes to ABBBBA
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