C++ - Introduction to the use of the string class

content

1. What is the string class

Second, the use of the string class

1. Common construction of string class objects

2. Capacity operation of string class objects

3. Access and traversal operations of string class objects

4. Modification operation of string class object

5, string class non-member function

6. Other functions


1. What is the string class

1. A string is a class that represents a sequence of characters

2. The standard string class provides support for such objects, whose interface is similar to that of the standard character container, but adds design features specifically for manipulating single-byte character strings.

3. The string class is using char (that is, as its character type, using its default char_traits and allocator type (see basic_string for more information on templates).

4. The string class is an instance of the basic_string template class . It uses char to instantiate the basic_string template class, and uses char_traits and allocator as the default parameters of basic_string (for more template information, please refer to basic_string).

5. Note that this class handles bytes independently of the encoding used: if used to handle sequences of multibyte or variable-length characters (such as UTF-8), all members of this class (such as length or size) and its , will still operate on bytes (rather than actual encoded characters)

Summarize:

1. string is a string class that represents strings

2. The interface of this class is basically the same as that of the conventional container , and some general operations specially used to manipulate strings are added.

3. String is actually at the bottom: alias of basic_string template class , typedef basic_string<char, char_traits, allocator> string;

4. Cannot operate on multi-byte or variable-length character sequences.

5. When using the string class, you must include #include header files and using namespace std.

Second, the use of the string class

1. Common construction of string class objects

function name Features

string s;

Constructs an empty string class object, that is, an empty string

string s1(const char* s);

copy the string pointed to by s

string s2(size_t n,char c);

Generate a string of n c characters

string s3(const string&s); Copy-construct with string class object

Specific use:

    string s;         // 构造空的string类对象s

	string s2("hello");//复制hello字符串给s2对象

	string s3(10, 'x');//生成10个x的字符串

	string s4(s2);     //用s2拷贝构造对象s4

2. Capacity operation of string class objects

function Features
size Returns the number of valid strings
length Returns the number of valid strings
capacity Returns the size of the total space
empty Check if a string is empty
clear empty string
reserve Reserve space for strings (kind of like malloc)
resize Change the number of valid characters to n, and fill the extra space with the character c (a bit like calloc)

Specific use: 

void test2()
{
	string s("hello");

	cout <<"size:"<< s.size() << endl;
	cout <<"length:"<< s.length() << endl;
	cout <<"capacity:"<< s.capacity() << endl;
	cout <<"empty:"<< s.empty() << endl;
}

The result is as follows: 

 For the clear function, just clear the string in s and set the size to 0, but do not change the size of the underlying space capacity :

void test2()
{
	string s("hello");

	cout <<"size:"<< s.size() << endl;
	cout <<"length:"<< s.length() << endl;
	cout <<"capacity:"<< s.capacity() << endl;
	cout <<"empty:"<< s.empty() << endl;
	cout << "----------" << endl;
	s.clear();
	cout << "size:" << s.size() << endl;
	cout << "capacity:" << s.capacity() << endl;
	cout << "empty:" << s.empty() << endl;

}

 Let's take a look at resize in detail :

void resize (size_t n);
void resize (size_t n, char c);

① Expand the capacity according to the given characters

void test3()
{
	string s("hello");
	s.resize(10, 'x');//将s中的有效字符个数增加到10个,后面多出的位置用x填充
	cout << "size:" << s.size() << endl;
	cout << "capacity:" << s.capacity() << endl;
	cout << s << endl;
}

The result is as follows: 

②The default given "\0" to fill the expansion

void test4()
{
	string s("hello");
	s.resize(15);//将s中的有效字符个数增加到15个,后面多出的位置用"\0"填充
	cout << "size:" << s.size() << endl;
	cout << "capacity:" << s.capacity() << endl;
	cout << s << endl;
}

 The result is as follows:

③ When the size is reduced, the characters will be truncated

void test5()
{
	string s("hello");
	s.resize(3);//将s中的有效字符个数减少到3个,只剩下原来的前三个
	cout << "size:" << s.size() << endl;
	cout << "capacity:" << s.capacity() << endl;
	cout << s << endl;
}

The result is as follows:

 Let's take a look at reserve in detail :

void reserve (size_t n = 0);

①When n is greater than the capacity of the current object, expand the capacity to n or greater than n

void test6()
{
	string s;
	cout << "size:" << s.size() << endl;
	cout << "capacity:" << s.capacity() << endl;
	cout << "----------------" << endl;
	s.reserve(100);//将原来的capacity扩大到100
	cout << "size:" << s.size() << endl;
	cout << "capacity:" << s.capacity() << endl;
}

The result is as follows:

 ②When n is less than the capacity, it will not shrink to the capacity

void test6()
{
	string s;
	cout << "size:" << s.size() << endl;
	cout << "capacity:" << s.capacity() << endl;
	cout << "----------------" << endl;
	s.reserve(100);//将原来的capacity扩大到100
	cout << "size:" << s.size() << endl;
	cout << "capacity:" << s.capacity() << endl;
	cout << "----------------" << endl;
	s.reserve(20);//不会将之前的capacity缩小
	cout << "size:" << s.size() << endl;
	cout << "capacity:" << s.capacity() << endl;
}

The result is as follows:

We can see that the capacity is not shrinking! ! !

Summarize:

① resize(size_t n) and resize(size_t n, char c) both change the number of valid characters in the string to n , the difference is that when the number of characters increases: resize(n) fills the excess with 0 The element space of , resize(size_t n, char c) fills the extra element space with the character c. Note: When resize changes the number of elements, if the number of elements is increased, the size of the underlying capacity may be changed. If the number of elements is reduced, the total size of the underlying space remains unchanged.

② reserve(size_t res_arg=0): Reserve space for string without changing the number of valid elements. When the parameter of reserve is less than the total size of the underlying space of string, reserve will not change the capacity size

3. Access and traversal operations of string class objects

function Features
operator [] (i) sum s [i]

Returns the character at position i, a call to a const string class object

begin+end begin gets an iterator for the first character, end gets an iterator for the next position of the last character
rbegin+rend rbegin gets the iterator of the first character in reverse, and rend gets the iterator of the next position of the last character in reverse
range for C++11 supports more concise range for traversal

operator[ ](i)

char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;

We know that the bottom layer of the string class string is actually implemented by an array, so we can traverse it by subscripting. The operator[ ](i) and s[i] here are actually exactly the same , but the latter is more convenient to use . They return a reference to the character at position pos in the string.

for example:

void test7()
{
	string s1("hello");
	const string s2("HELLO");
	cout << s1 << " " << s2 << endl;
	cout << s1[0] << " " << s2[0] << endl;

	s1[0] = 'x';
	cout << s1 << endl;

	//s2[0] = 'x';const类对象不能修改
}

Three traversal operations: (commonly used)

①The usage of operator[ ]

void test8()
{	
	string s1("hello");
	string s2(s1);//拷贝构造
	for (size_t i = 0; i < s2.size(); ++i)
	{
		cout << s2.operator[](i) << " ";
		cout << s2[i] << " ";
	}
	cout << endl;
	for (size_t i = 0; i < s2.size(); ++i)
	{
		s2[i] += 1;//支持修改
	}
	cout << s2 << endl;
}

②Iterator

Note: For the time being, the iterator is imagined as a pointer-like type

void test9()
{
	string s("hello");
	//迭代器的用法
	string::iterator it = s.begin();
	while (it !=s.end())
	{
		cout << *it << endl;
		++it;
	}
}

③ Range for

In fact, the bottom layer of the range for is to process it into an iterator

void test10()
{
	string s("hello");
	for (auto ch : s)
		cout << ch << endl;
	//把s中的每个字符取出来,赋值给ch,不需要++,判断结束,自动往后迭代
}

4. Modification operation of string class object

function Features
push_back Insert the character c at the end of the string
append append string after string
operator+= append string after string
c_str Returns a C format string
find+npos Starting from the position of the string pos, look for the character c, and return the position of the character in the string
rfind Starting from the position of the string pos, look forward to the character c, and return the position of the character in the string
substr In the string, starting at position pos, truncate n characters, then return it

①push_back

void push_back (char c);
void test11()
{
	string s("xxx");
	cout << s << endl;
	s.push_back('H');
	s.push_back('E');
	s.push_back('L');
	s.push_back('L');
	s.push_back('O');
	cout << s << endl;//将HELLO依次拼接到xxx后面
}

The result is as follows:

②append 

string& append (const string& str);
string& append (const char* s);
void test12()
{
	string s1("hello");
	string s2("C++");
	s1.append(s2);//直接拼接一个对象字符串

	cout << s1 << endl;
	s1.append("haha");//直接拼接一个字符串
	cout << s1 << endl;
}

 ③ operator+= (this is the most commonly used function)

string& operator+= (const string& str);
string& operator+= (const char* s);
string& operator+= (char c);
void test13()
{
	string s1("hello");
	string s2("world");
	s1 += s2;
	cout << s1 << endl;

	s1 += "xxx";
	cout << s1 << endl;

	s1 += 'A';
	cout << s1 << endl;
}

The result is as follows: 

 ④c_str

const char* c_str() const;
void test14()
{
	string s("hello");
	//以语言的格式打印字符串
	cout << s.c_str() << endl;
}

The result is as follows:

 ⑤find function

static const size_t npos = -1;//其实npos就是size_t的最大值

size_t find (const string& str, size_t pos = 0) const;
	
size_t find (const char* s, size_t pos = 0) const;
	
size_t find (const char* s, size_t pos, size_t n) const;
	
size_t find (char c, size_t pos = 0) const;
void test15()
{
	string s1("http://www.cplusplus.com/reference/string/string/find/");
	
	size_t pos1 = s1.find("com");//正向查找com字符串
	cout << pos1 << endl;

	string s2("http");
	size_t pos2 = s1.find(s2);//正向查找与s2对象匹配的字符串
	cout << pos2<< endl;

	size_t pos3 = s1.find('p');//正向查找字符p
	cout << pos3 << endl;
}

 Results show:

 ⑥rfind

size_t rfind (const string& str, size_t pos = npos) const;
	
size_t rfind (const char* s, size_t pos = npos) const;

size_t rfind (const char* s, size_t pos, size_t n) const;
	
size_t rfind (char c, size_t pos = npos) const;
void test16()
{
	string s1("http://www.cplusplus.com/reference/string/string/find/");

	size_t pos1 = s1.rfind("string");//反向查找是s1中第一次出现的string的首位置
	cout << pos1 << endl;

	string s2("cplusplus");
	size_t pos2 = s1.rfind(s2);//反向查找s1中与s2对象匹配的首位置
	cout << pos2 << endl;

	size_t pos3 = s1.rfind('h'); //反向查找s1中h字符
	cout << pos3 << endl;
}

 Results show:

⑦substr

string substr (size_t pos = 0, size_t len = npos) const;
void test17()
{
	//获取file的后缀
	string file("string.cpp");
	size_t pos = file.rfind('.');//反向查找 . 点
	string suffix(file.substr(pos,file.size()-pos));//从点开始,包括点的后面部分
	cout << suffix << endl;
}

result:

5, string class non-member function

function

Features

operator+ Use as little as possible, because it is returned by value, resulting in low copy efficiency
operator>> Stream insertion operator overloading
operator<< Stream extraction operator overloading
getline get a line of string
relational operators size comparison

I/O problem: 

void test18()
{
	string s;
	cin >> s;//输入hello world
	cout << s << endl;//只会打印hello
}

 We know that the standard input of cin will stop reading when a space or \n is read from the keyboard. At this time, the getline function will be used.

istream& getline (istream& is, string& str, char delim);
//从is中读取字符串,储存在str对象中,直到遇到delim界限符或者\n停止

istream& getline (istream& is, string& str);
//从is中读取字符串,储存在str对象中,直到遇到\n停止
void test18()
{
	string s1;
	getline(cin,s1,'e');//输入hello world
	cout << s1 << endl;//输出h
}
void test18
{
	string s2;
	getline(cin, s2);//输入hello world
	cout << s2 << endl;//输出hello world
}

Size comparison question:

void test19()
{
	string s1("hello");
	string s2("string");
	cout << (s1 > s2) << endl;//输出0
}

It's a little different here. The size of the ASCII code value of the first character is compared. If the first one is equal, the second one is compared, and a bool value is returned, and so on.

6. Other functions

It is more commonly used when doing OJ questions

stoi - convert string to integer

void test20()
{
	int val = stoi("12345");
	cout << val << endl;
}

There are many similar functions: stod stoll stof, etc., if you are interested, you can learn about it yourself

to_string - other types are converted to strings

void test21()
{
	string str = to_string(3.14);
	cout << str << endl;
}

Thanks for watching!

Guess you like

Origin blog.csdn.net/weixin_57675461/article/details/123405293