[Advanced Road to C++] Teach you step by step how to use the string class interface

Preface

There is no string type in C language, but we often operate on strings. Therefore, in C++, the string class was proposed to operate on strings. Let’s take a look at it below.

Basic understanding

  • String is a class that represents a sequence of characters
  • Because the string class was implemented earlier than STL , it is not in the container.
  • The use of the string class and the container are basically implemented by calling the interface .
  • The string class is an instantiation of the basic_string template , and the data type of the operation is char .

At the bottom level, string is actually: an alias of the basic_string template class——
typedef basic_string<char, char_traits, allocator>string;

  • The string class can only operate on a single character and cannot operate on multiple characters at once.

Basic use

Classes in the library - then include header files

#include<string>

To use classes from the library:

  1. Expand namespace
using namespace::std;
  1. Or specify the scope
std::string A;

1. Constructor

default constructor

function:

string()

Function: Initialized to an empty string, followed by a certain length of 0 or \0 .

example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string A;
	return 0;
}

Open the monitoring window and see the results after initialization:
Insert image description here

  • All we are shown is an empty string.
  • What about actually?
    Insert image description here
  • It is actually an array, the space is 16 bytes, and the first 4 elements are initialized to 0——\0 .

copy constructor

function:

string(const string&s)
//这里的const将权限缩到最小,所以既可以传string又可以传const string

Function: copy construction.
Example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string A;
	string B(A);
	string C = A;
	//这里也是拷贝构造,因为是用一个已经初始化的对象初始化另一个正在初始化的对象。
	return 0;
}

Other constructors

①string(const char* s)

function:

string(const char* s) 

Function: Initialize a string class with a string.

example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string B("hello world");
	return 0;
}

②string(size_t n, char c)

function:

string(size_t n, char c)

Function: Initialize the string class to n c characters.

example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string B(6,'x');
	cout << B << endl;
	return 0;
}

Results of the:
Insert image description here

③string (const string& str, size_t pos, size_t len = npos)

function:

string (const string& str, size_t pos, size_t len = npos)
static const size_t npos = -1;//-1就等于FFFFFFFF

Function: Copy the contents of a string class starting from the pos position to npos length characters to another string class.

example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string B("hello world");
	string A(B, 0, 5);
	//这里的0按照数组的下标进行计算的。
	//5是包括从0位置开始的5个元素。
	cout << A << endl;
	return 0;
}

2. Capacity interface

①Size and length

  • Note: size and length are both valid characters for the string class.

Valid characters are characters except \0.

Example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string A("hello");
	cout << A.size() << endl;
	cout << A.length() << endl;
	return 0;
}

Supplement: size is designed to cater to containers, because only strings are called length, and everything else is called size.

②max_size

function:

size_t max_size() const;

Function: The maximum length that a string can reach.
example:

#include <iostream>
#include <string>
int main()
{
    
    
	string A;
	cout<<A.max_size()<<endl;
	return 0;
}

Insert image description here

③capacity

  • Function: Find the maximum capacity of currently valid characters in a character class.

Example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string A("hello");
	cout << A.capacity() << endl;
	return 0;
}

Results of the:
Insert image description here
Insert image description here

  • But we clearly opened 16 bytes, but here it says that 15 bytes were opened. Why?

  • Because: we did not count the space after \0 and after, only the space that can store valid characters .

So what if we write it like this?

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string A("hel\0lo\0");
	cout << A.capacity() << endl;
	return 0;
}

result:
Insert image description here

The recognized string is like this:
Insert image description here

  • Therefore: the string class only recognizes up to the first \0, and the subsequent ones are not considered.

So if we store 20 bytes, will the string class expand our space?

example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string A("hello");
	int prev_capacity = A.capacity();
	cout << prev_capacity << endl;
	for (int i = 0; i < 4; i++)
	{
    
    
 		while (A.size() != prev_capacity)
		{
    
    
			A += 'x';
		}
		A += 'x';
		cout << A.capacity() << endl;
		prev_capacity = A.capacity();
	}
	return 0;
}

Execution results:
Insert image description here
We can see that the capacity will be expanded here, and the first expansion is a 2-fold expansion (counting \0), and the subsequent expansion is close to a 1.5-fold expansion. (VS2019)
Let’s switch to the Linux platform for testing:
Insert image description here

  • It is not difficult to see that the expansion here is doubled .

④empty

function:

bool empty() const;
//说明:加了const,所以使用empty是不会对string类进行修改的。

Function: Check whether the string is empty, return true if it is empty, and return false in other cases.

example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string A("\0");
	if (A.empty())
	{
    
    
		printf("YES\n");
	}
	else
	{
    
    
		printf("NO\n");
	}
	return 0;
}

result:
Insert image description here

⑤clear

function:

void clear();

Function: Reduce the characters in the string to make it an empty string, that is, the length of the string is 0.

example:

#include<iostream>
#include<string>
using namespace::std;
int main()
{
    
    
	string A("hello world");
	A.clear();
	if (A.empty())
	{
    
    
		printf("YES\n");
	}
	else
	{
    
    
		printf("NO\n");
	}
	return 0;
}

result:
Insert image description here

⑥reserve

function:

void reserve (size_t n = 0);

Function: Reserve n space for strings. When n is greater than capacity, the capacity will be expanded. In other cases, the original capacity will be used.
Result: Make the capacity of string greater than or equal to n.

  • When n is less than capacity, this is a non-binding request, so the container's execution is based on actual compiler optimizations and leaves a result with capacity greater than or equal to n.
  • Generally speaking, the compiler may shrink the string when it feels that the space of the string is much smaller than the capacity.
#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello world");
	A.reserve(20);
	cout <<A<< endl;
	return 0;
}

Before execution: capacity——15
Insert image description here
After execution: capacity——31
Insert image description here

⑦resize

function:

void resize (size_t n);
void resize (size_t n, char c);
//这两个是函数重载

Function:

  • When n is less than size, all characters with more than n will be deleted, and those with less will not be processed.
  • When n is greater than size, if there is no second parameter, the part greater than size will be filled with \0. If there is a second parameter, the part greater than size will be filled with the value of the second parameter.

Example 1: Less than size

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello world");
	A.resize(1,'x');//这里的x其实没啥用
	cout << A << endl;
	return 0;
}

Result:
Insert image description here
Example 2: Greater than size

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello world");
	A.resize(20,'x');
	cout << A << endl;
	return 0;
}

result:
Insert image description here

3. Modify the interface

①+=

function:

string& operator+= (const string& str);
string& operator+= (const char* s);
string& operator+= (char c);

Function: += a string/character/string class

example:

#include <iostream>
#include <string>

int main()
{
    
    
	string A;
	A += "hello";
	A += ' ';
	string B("world");
	A += B;
	cout << A << endl;
	return 0;
}

operation result:
Insert image description here

②[]

function:

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

Function: Access the character at the subscript position of the string.
example:

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello");
	char a = A[0];
	cout << a << endl;
	return 0;
}

result:
Insert image description here

Note: [ ] will report an error (assert) if it crosses the boundary, and throw an exception if at crosses the boundary.

③push_back

function

void push_back (char c);

Function: Append a character
after the end of string . Example:

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello");
	A.push_back('x');
	cout << A << endl;
	return 0;
}

result:
Insert image description here

④append

function:

string& append (const string& str);

string& append (const string& str, size_t subpos, size_t sublen);

string& append (const char* s);
	
string& append (const char* s, size_t n);

string& append (size_t n, char c);

Function: Append n characters/(the first n characters) string/string (from subpos position to sublen position) after the specified string.

example:

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello world");
	string B(" hello");
	A.append(B,0,6);
	cout << A << endl;
	A.append(B);
	cout << A << endl;
	A.append(" hello", 0, 6);
	cout << A << endl;
	A.append(6, 'x');
	cout << A << endl;
	return 0;
}

result:
Insert image description here

⑤c_str

function:

const char* c_str() const;

Function: Returns a string, type is const char *.
example:

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello");
	const char* a = A.c_str();
	cout << a << endl;
	return 0;
}

result:
Insert image description here

⑥ find

function:

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;
//pos是要查找string的下标,n是要在指定字符串中查找的长度。
//size_t,如果成功返回一个匹配成功的下标,如果失败返回-1(转换为无符号整形)。

Function: Starting from the specified pos subscript position of the string class, search backwards for the character c position of the target [string/string (specify the first n characters to search)/character], and return its position.
Note: The search is for characters (string, inside string).
example:

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello world");
	string B("world");
	cout << A.find(B, 0)<<endl;
	cout << A.find("world", 0) <<endl;
	cout << A.find("world", 0, 5) <<endl;
	cout << A.find('w', 0) <<endl;
	return 0;
}

result:
Insert image description here

⑦rfind

function:


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;
原理:同find

Function: Starting from the specified pos subscript position of the string class, search forward for the character c position of the target [string/string (specify the first n characters to search)/character], and return its position.

example:

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello world");
	string B("world");
	cout << A.rfind(B, 5)<<endl;
	cout << A.rfind("world", 10) <<endl;
	cout << A.rfind("world", 10, 5) <<endl;
	cout << A.rfind('w', 10) <<endl;
	return 0;
}

result:
Insert image description here

⑧find_first_of

function


size_t find_first_of (const string& str, size_t pos = 0) const;
	
size_t find_first_of (const char* s, size_t pos = 0) const;

size_t find_first_of (const char* s, size_t pos, size_t n) const;

size_t find_first_of (char c, size_t pos = 0) const;

Function: Starting from the pos position in the string class, search for any character related to the first n positions of the string.
example:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    
    
	string str("hello world");
	size_t pos = str.find_first_of("wo", 0, 1);
	//在hello world 中的下标的0位置开始找,找与“wo”的前1个字符相同的字符。
	//即在hello world 中找w。
	cout << pos << endl;
	return 0;
}

4. Iterator——iterator

basic concept

The function of an iterator is to access elements in a container (a data structure used to save elements) , so using an iterator, we can access the elements in the container.

①begin and end

function:

      reverse_iterator rbegin();
const_reverse_iterator rbegin() const;

Function: Get the beginning position of string.

function:

 iterator end();
 const_iterator end() const;

Function: Get the next position of the last valid character of string, which is usually \0.

example:

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello world");
	string::iterator it = A.begin();
	//当A是const修饰的类时,我们就要用string::const_iterator迭代器
	while (it != A.end())
	{
    
    
		cout << *it << " " ;
		it++;
	}
	return 0;
}

result:
Insert image description here

②rbegin and rend

function:

      reverse_iterator rbegin();
const_reverse_iterator rbegin() const;

Function: Get the position of the last valid character.
function:

      reverse_iterator rend();
const_reverse_iterator rend() const;

Function: Get the previous position of the first character.

example:

#include <iostream>
#include <string>
int main()
{
    
    
	string A("hello world");
	string::reverse_iterator it = A.rbegin();
	while (it != A.rend())
	{
    
    
		cout << *it << " " ;
		it++;
	}
	return 0;
}

Note: rbegin + 1 here is
the result of adding 1 backwards:
Insert image description here
please see the document for the rest of the content

5. Non-member functions

①getline

function


istream& getline (istream& is, string& str, char delim);

istream& getline (istream& is, string& str);

Function:
Input/output the string through the stream. The input/output ends when encountering the delim termination character. If not written, the default is \n. This solves the problem of spaces encountered in our input.

For scanf to read a line you can

scanf("%[^\n]",str);//意为读取到\n结束。

for gets

gets(str);

②stoi——String conversion series

Note: This series will introduce this one, you can learn about the others by yourself.

function:

int stoi (const string&  str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);

Function:
Convert the first idx numeric characters of string into integer in base system (default is decimal system).
example:


#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

int main()
{
    
    
	std::string str_dec = "2001, A Space Odyssey";
	std::string str_hex = "40c3";
	std::string str_bin = "-10010110001";
	std::string str_auto = "0x7f";

	std::string::size_type sz;   // alias of size_t

	int i_dec = std::stoi(str_dec, &sz);
	int i_hex = std::stoi(str_hex, nullptr, 16);
	//不使用第二个参数传入空指针即可。
	int i_bin = std::stoi(str_bin, nullptr, 2);
	int i_auto = std::stoi(str_auto, nullptr, 0);
	std::cout << str_dec << ": " << i_dec << "\n";
	std::cout << str_hex << ": " << i_hex << '\n';
	std::cout << str_bin << ": " << i_bin << '\n';
	std::cout << str_auto << ": " << i_auto << '\n';
	return 0;
}

Guess you like

Origin blog.csdn.net/Shun_Hua/article/details/130859705