[C++ From Bronze to King] Part VII: First Acquaintance of STL's string Class

Series Article Directory

foreword

1. What is STL

STL(standard template libaray-standard template library): is an important part of the C++ standard library, not only a reusable component library, but also a software framework including data structures and algorithms.

Second, the six components of STL



3. Defects of STL

  • STL library updates are too slow. This is a serious complaint. The last version is C++98, and the middle C++03 is basically revised. It has been 13 years since C++11 came out, and the STL has been further updated.
  • None of the STL currently supports thread safety. In a concurrent environment, we need to lock ourselves. And the granularity of the lock is relatively large.
  • STL's extreme pursuit of efficiency leads to internal complexity. Such as type extraction, iterator extraction.
  • The use of STL will have the problem of code expansion. For example, using vector/vector/vector will generate multiple codes. Of course, this is caused by the template syntax itself.

Fourth, why learn the string class

1. Strings in C language

In C language, a string is a collection of some characters ending with '\0'. For the convenience of operation, some str series library functions are provided in the C standard library, but these library functions are separated from strings and are not very It is in line with the idea of ​​​​OOP, and the underlying space needs to be managed by users themselves, and may be accessed beyond the bounds if they are not careful.

2. Two interview questions

String to Integer (atoi)

String addition

In OJ, questions about strings basically appear in the form of the string class, and in routine work, the string class is basically used for simplicity, convenience, and speed, and few people use the string manipulation functions in the C library.

3. The string class in the standard library

Documentation of the string class

  • Summarize:
  • string is a string class that represents strings.
  • The interface of this class is basically the same as that of a regular container, with the addition of some general operations specially used to manipulate string s.
  • String is actually under the hood: an alias for the basic_string template class, typedef basic_string<char, char_traits, allocator>string.
  • Cannot operate on sequences of multibyte or variable-length characters.

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

4. Common interface description of string class

1. Common construction of string class objects

#define _CRT_SECURE_NO_WARNINGS   1
#include<iostream>
#include<string.h>
#include<assert.h>
using namespace std;
#include<string>
int main()
{
	//4 constructors
	string s1;
	string s2("hello");
	string s3(s2);
	string s4(5, 'a');
	string s5 = "hello";
	string s6 = s2;

	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	//The destructor first frees s4, then s3, then s2, then s1
	cout << s5 << endl;
	cout << s6 << endl;

	s1 = s2;
	cout << s1 << endl;
	return 0;
}

void TestString1()            //Constructor
{
	string s1;                 //ok
	string s2("bit");          //ok
	string s3(s2);             //ok
	string s4("bit", 1);
	string s5("bit education", 1, 2);
	string s6("bit education", 1, string::npos); //npos is a static global variable with -1's complement infinity
	string s7("bit education", 1,20);
	string s8(5, 'a');

	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	cout << s5 << endl;
	cout << s6 << endl;
	cout << s7 << endl;
	cout << s8 << endl;

	s1 = s8;                //assignment ok
	cout << s1 << endl;
}

2. Capacity operation of string class objects

void TestString7() //Capacity operation of string class
{
	string s1("bit education");
	string s2("C++");
	cout << s1.size() << endl;
	cout << s2.size() << endl;
	cout << s1.length() << endl;
	cout << s2.length() << endl;

	cout << s1.max_size() << endl;
	cout << s2.max_size() << endl;

	cout << s1.capacity() << endl;
	cout << s2.capacity() << endl;

	s1.clear();                  //size is reduced to 0
	cout << s1 << endl;
	cout << s1.capacity() << endl;
}


Comparison of reserve open space, reserve is not used

void TestString8()
{
	string s;
	size_t sz = s.capacity();
	cout << "making s grow:" << endl;
	for (size_t i = 0; i < 100; i++)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed:" << sz << endl;
		}
	}
}


The comparison of reserve open space, use reserve

void TestString9 ()
{
	string s;
	s.reserve(100);
	size_t sz = s.capacity();
	cout << "making s grow:" << endl;
	for (size_t i = 0; i < 100; i++)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed:" << sz << endl;
		}
	}
}


resize opens space but fills with characters by default

void TestString10()
{
	string s;
	s.resize(100, 'a');
	size_t sz = s.capacity();
	cout << "making s grow:" << endl;
	for (size_t i = 0; i < 100; i++)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed:" << sz << endl;
		}
	}
}

3. Access and traversal operations of string class objects


[]+ subscript traversal, overloaded += operator ---- append

void TestString2()         //[]+ subscript traversal, overloaded += operator ---- append
{
	string s1("bit");

	s1 += 'e';
	cout << s1 << endl;
	s1 += ' ';
	s1 += "ducation";
	cout << s1 << endl;

	//[]+ subscript traversal method
	for (size_t i = 0; i < s1.size(); i++)   //read
	{
		cout << s1[i] << " ";
	}
	cout << endl;

	for (size_t i = 0; i < s1.size(); i++)  //write, modify characters
	{
		s1[i] = s1[i] + 1;
	}
	for (size_t i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " ";
	}
	cout << endl;
}


iterator traversal

void TestString3()    //iterator traversal
{
	string s1("bit education");
	string::iterator it = s1.begin();
	//auto it=s1.begin();auto automatically deduces that it is an iterator
	//vector<int>::iterator it=s1.begin();
	//read
	while (it != s1.end())
	{
		cout << *it << " ";
		it++;
	}
	cout << endl;

	//Write
	it = s1.begin();
	while (it != s1.end())
	{
		*it = *it + 2;
		it++;
	}
	cout << s1 << endl;

	vector<int> v1;
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);
	vector<int>::iterator vit = v1.begin();
	while (vit != v1.end())
	{
		cout << *vit << " ";
		vit++;
	}
	cout << endl;
}


The traversal of range for C++11 principle is iterator

void TestString4()    //The traversal of range for C++11 principle is iterator
{
	string s1("bit education");
	for (auto s : s1)   //Take out the characters in the container s1 in turn to s
	{
		cout << s << " ";
	}
	cout << endl;

	for (auto s : s1)
	{
		s = s + 1;
		cout << s << " ";
	}
	cout << endl;
}


Reverse iterator, traverse backwards

void TestString5()    //Reverse iterator, traverse backwards
{
	string s1("bit education");
	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		cout << *rit << " ";
		rit++;
	}
	cout << endl;
}


For parameters of const type, use const type iterators, and const type iterators can only read

int String2Int(const string& nums)  //For parameters of const type, use const type iterators, and const type iterators can only read
{
	int val = 0;
	string::const_iterator it = nums.begin();
	while (it != nums.end())
	{
		//*it = 'a';
		val = val * 10;
		val = val + (*it - '0');
		it++;
	}
	return val;
}
void TestString6()//simple string to integer
{
	string nums("12345");
	int ret = String2Int(nums);
	cout << ret << endl;
}

4. Modify operation of string class object

void TestString11()  //Modify operations on objects of class string
{
	string s("bite");
	cout << s<< endl;
	s.push_back(' ');
	cout << s << endl;
	s.append("education");
	cout << s << endl;
	s += "!";
	cout << s << endl;

	s.insert(s.begin(), 'B');
	cout << s << endl;
	s.insert(0, "A");
	cout << s << endl;

	s.erase(2, 3);
	cout << s << endl;
	s.erase(s.begin(),s.end());
	cout << s << endl;

}


c_str

void TestString12()
{
	//Get the first address of the character array and traverse it in the form of a C string
	string s1("bie education");
	const char* str = s1.c_str();
	while (*str)
	{
		cout << *str << " ";
		str++;
	}
	cout << endl;
	s1 += '\0';
	s1 += "hello";
	cout << s1 << endl;           //The string overload operator<< called will output all characters in the object array
	cout << s1.c_str() << endl;   //Direct output of const char* ends with \0

	//print all characters 256
	for (unsigned char ch = 0; ch < 256; ch++)
	{
		cout << ch << " ";
	}
	cout << endl;
}


rfind and substr

void TestString13()   //find gets the suffix of the file, rfind can search backwards
{
	string s1("string.cpp.zip");
	string s2("string.c");
	string s3("string.txt");
	size_t pos1 = s1.find('.');

	if (pos1 != string::npos)
	{
		cout << s1.substr(pos1) << endl;
	}
	size_t pos2 = s2.find('.');
	if (pos2 != string::npos)
	{
		cout << s2.substr(pos2) << endl;
	}
	size_t pos3= s3.find('.');
	if (pos3 != string::npos)
	{
		cout << s3.substr(pos3) << endl;
	}

	//Protocol Domain Name Resource Name
	string stringcpp("http://www.cplusplus.com/reference/string/string/find/");

	string &url = stringcpp;
	size_t pos4 = url.find(":");
	if (pos4 != string::npos)
	{
		cout << url.substr(0,pos4) << endl;
	}
	size_t pos5 = url.find('/', pos4 + 3);
	if (pos5 != string::npos)
	{
		cout << url.substr(pos4 + 3, pos5 - pos4-3) << endl;
	}
	cout << url.substr(pos5 + 1) << endl;
}

5. string class non-member function

void TestString14()
{
	string s1("hello");
	string ret1 = s1 + "world";   //Overloading + does not change s1
	string ret2 = s1 += "world";  //Overloading += will change s1
	cout << ret1 << endl;
	cout << ret2 << endl;

	string s2("aabbc");
	string s3("bbbdd");
	cout << (s2 > s3) << endl;
}

Summarize

The above is what I want to talk about today. This article only briefly introduces the use of the string class, and string provides a lot of functions and methods that can make us process data quickly and conveniently, which is very convenient, so we must master it. Next is the mock implementation of the string class. In addition, if there are any problems with the above, please understand my brother's advice, but it doesn't matter, the main thing is that you can persevere, and I hope that there are classmates who study together to help me correct me, but if you can please tell me gently, love and peace are eternal themes , love you all.

Tags: C++ string STL

Posted by jokerfool on Wed, 27 Jul 2022 22:09:47 +0530