C++ STL string class

Table of contents

1. Why learn the string class

(1) Strings in C language

(2) The string class in the standard library

2. Common interface description of string class

(1) Common constructions of string class objects

(2) Capacity operation of string objects

1.size(),length().

2. capacity()

3.empty()

 4.clear()

 5.reserve()

 6.resize()

(3) Access and traversal operations of string class objects

 1.operator[ pos ] ,at(size_t pos)

 2.back(),front()

(4) Iterator of string class

1.begin(),end()

2.rbegin() ,rend()

3. Range for

(5) Modification operation of string class object

1.push_bank( )

 2.append()

3.operator +=

 4.insert ()

 5.erase()

6.swap()

(6) String correlation algorithm

1.c_str()

 2.find()

3.substr()

(7) Non-member function overloading

1.getline()


1. 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, the C standard library provides some library functions of the str series, but these library functions are separated from the string. It conforms to the idea of ​​OOP, and the underlying space needs to be managed by the user, and it may be accessed out of bounds if you are not careful.

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

(2) The string class in the standard library

string class documentation

  1. String is a class representing a sequence of characters
  2. The standard string classes provide support for such objects, with an interface similar to that of the standard character containers, but with added design features specifically for manipulating single-byte character strings.
  3. The string class is using char (i.e. as its character type, using its default char_traits and allocator types (see basic_string for more information on templates).
  4. The string class is an instance of the basic_string template class, which uses char to instantiate the basic_string template class, and uses char_traits and allocator as the default parameters of basic_string (see basic_string for more template information).
  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 iteration , will still operate on bytes (rather than actual encoded characters).

Summary:
1. string is a string class that represents strings
2. The interface of this class is basically the same as that of conventional containers, and some conventional operations specially used to manipulate strings are added.
3. String is actually an alias of the basic_string template class at the bottom layer, typedef basic_string<char, char_traits, allocator>string;
4. Cannot operate sequences of multi-byte or variable-length characters

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

2. Common interface description of string class

(1) Common constructions of string class objects

string() (emphasis) Create an empty string type object, that is, an empty string
string(const char* s) (emphasis) Use C-string to construct string class object
string(size_t n, char c) The string class object contains n characters c
string(const string&s) (emphasis) copy constructor
#include<iostream>
#include<string>
using namespace std;
int main()
{
	//创建空字符串
	string str1;
	cout << str1 << endl;
	//使用字符串构造对象
	string str2("hello world");
	cout << str2 << endl;
	//使用n个字符构造对象
	string str3(15, '*');
	cout << str3 << endl;
	//拷贝构造函数
	string str4(str2);
	cout << str4 << endl;

	return 0;
}

(2) Capacity operation of string objects

Courseware code/C++ courseware V6/string interface test and use/TestString.cpp · will/C++ class- Gitee.com

1.size(),length().

Both size() and lenth return the effective length of the string.

Note: We generally use length when expressing the length of a string. The reason for introducing size() is to be consistent with the interface of other containers. In general, size() is basically used.

int main()
{
	string str("hello world");
	cout << str.size() << endl;
	cout << str.length() << endl;

	return 0;
}

2. capacity()

capacity() returns the total space size of the string object, because the string itself can be expanded.

int main()
{
	string str("hello world");
	cout << str.size() << endl;
	cout << str.length() << endl;
	cout << str.capacity() << endl;

	return 0;
}

3.empty()

If the detection string is released as an empty string, it returns true, otherwise it returns false.

int main()
{
	string str("hello world");
	string str1;
	cout << str.empty() << endl;
	cout << str1.empty() << endl;

	return 0;
}

 4.clear()

Clear valid characters.

Note: clear() only clears the valid characters in the string, and does not change the size of the underlying space.

int main()
{
	string str("hello world hello world hello ");
	cout << "clear前:" << str <<" 容量:" << str.capacity() << endl;
	str.clear();
	cout << "clear前:" << str << "容量:" << str.capacity() << endl;
	return 0;
}

 5.reserve()

Reserve space for strings. In some cases, if we know the size of the string in advance, we can open space for the string in advance to avoid the efficiency consumption caused by subsequent expansion.

Note: The actual space after application will be larger than the space we applied for, which is also a protection mechanism. But if the space we reserve is smaller than the original space, the function will be optimized at this time, and the table will be modified appropriately according to the length of the string we store.

 6.resize()

resize(size_t n) and resize(size_t n, char c) both change the number of effective characters in the string to n, the difference is that when the number of characters increases: resize(n) fills the excess with 0 Element space, resize(size_t n, char c) uses character c to fill the extra element space. 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. If n is less than the length of the string, delete the string and keep the first n.

int main()
{
	string str("abcde");
	cout << str << endl;
	//扩容+初始化
	str.resize(str.size() + 5, '#');
	cout << str << endl;
	//减小长度
	str.resize(4);
	cout << str << endl;

	return 0;
}

(3) Access and traversal operations of string class objects

 1.operator[ pos ] ,at(size_t pos)

operator [ ] returns the character at position pos, and is called by const string class object. operator[ ] is an operator overload for [ ], just like array access.

Note: The difference between the two is that in terms of handling out-of-bounds, operator[ ] uses assertion processing, while at(pos) throws an exception.

int main()
{
	string str("hello");
	for (int i = 0; i < str.size(); i++)
	{
		cout << str[i] << " ";
	}
	cout << endl;
	for (int i = 0; i < str.size(); i++)
	{
		cout << str.at(i) << " ";
	}
	return 0;
}

 2.back(),front()

back(): returns the last character, front(): returns the first character.

(4) Iterator of string class

1.begin(),end()

begin(): Returns an iterator that points to the beginning character of the string.

end(): Returns an iterator that points to the end character of the string.

An iterator is also a thing used to traverse objects. It has its own type iterator. For begin() and end(), it also has its own const version, which is a read-only iterator. The use of string iterators is similar to that of pointers.

At present, it can be understood that as we continue to learn STL, we will have a deeper understanding of iterators.

int main()
{
	string str("helloworld");
	//非const迭代器,可读,可写
	for (string::iterator it = str.begin();it!=str.end();it++)
	{
		*it = '*';
	}
	for (string::iterator it = str.begin(); it != str.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
	//const 迭代器 仅可读
	const string str1("helloworld");
	for (string::const_iterator it = str1.begin(); it != str1.end(); it++)
	{
		cout << *it << " ";
	}
	return 0;
}

2.rbegin() ,rend()

rbegin(): returns a reverse iterator to start in reverse, returns a reverse iterator pointing to the last character of the string (ie its reverse beginning), the reverse iterator iterates backwards: increasing the iterator will replace them Move to the beginning of the string.

rend(): Returns a reverse iterator pointing to the theoretical element before the first character of the string (considered its reversed end).

The type of the reverse iterator is reverse_iterator , and both provide the const version.

int main()
{
	string str("helloworld");
	
	for (string::reverse_iterator it = str.rbegin(); it != str.rend(); it++)
	{
		cout << *it << " ";
	}
	return 0;
}

 

It is very inconvenient to write the type of iterator, we can use auto to automatically identify it.

3. Range for

The range for is to take out the characters of the str object one by one and put them in c. The bottom layer is still the iterator used.

int main()
{
	string str("helloworld");

	for (auto c : str)
	{
		cout << c << " ";
	}
	return 0;
}

(5) Modification operation of string class object

1.push_bank( )

Insert the character c at the end of the string.

int main()
{
	string str("hello");
	cout << str << endl;
	str.push_back('w');
	str.push_back('o');
	str.push_back('r');
	str.push_back('l');
	str.push_back('d');
	cout << str<<endl;
	return 0;
}

 2.append()

Appends a string to the end of the string, and multiple versions are also provided:

string& append (const string& str): Append a string str.

string& append (const string& str, size_t subpos, size_t sublen): append sublen characters after the pos position of the string str.

string& append (const char* s): Append a C string, (that is, a string ending with '/0').

string& append (const char* s, size_t n): Append the last n characters of the C string s.

string& append (size_t n, char c): append n characters c  

int main()
{
	string str;
	string str1;
	cout << str << endl;
	string str2 = "Writing ";
	//str1追加str2的第四个位置的后三个字符
	str1.append(str2, 4,3);
	//str追加str2
	str.append(str2);
	cout << str << endl;
	cout << str1 << endl;
	//str2z追加一个C字符串
	str2.append("work");
	cout << str2 << endl;
	//str2追加一个c字符串的前两个字符
	str2.append("hello", 2);
	cout << str2 << endl;
	//str2追加10个‘#’
	str2.append(10, '#');
	cout << str2 << endl;

	return 0;
}

3.operator +=

 For the above push_bank and append, they are not used much in the string class. We generally use operator+= to append strings or characters.

example:

int main()
{
	string str1("hello");
	string str2("world");
	str1 += str2;
	
	cout << str1 << endl;

	return 0;
}

 4.insert ()

The string insertion function can support inserting a fixed number of characters and strings at a certain position or iterator position.

 example:

int main()
{
	string str1("hello");
	string str2("world");
	int pos = 0;
	//1.在pos位置插入一个 string 
	str2.insert(pos, str1);
	cout << str2 << endl;

	string str3("bcde");
	int size = 5;
	//2.在pos位置插入size个字符a
	str3.insert(pos, size, 'a');
	cout << str3 << endl;

	string str4("bcde");
	//3.插入位置还可以是迭代器
	str4.insert(str4.begin(), 10, 'A');
	cout << str4 << endl;

	string str5("world");
	const char* cstr = "hello ";
	//3.在pos位置插入一个 C风格字符串。
	str4.insert(pos,cstr);
	cout << str5 << endl;

	return 0;
}

 Note: insert, when inserting, especially when inserting at the front of the string, there will be character movement consumption. It is equivalent to the head plug of the sequence table.

 5.erase()

rases part of the string, shortening its length.

example:

int main()
{
	int pos = 5;
	int size = 3;
	string str1("hello   C++");
	string str2 = str1;
	cout << "erase前str1:" << str1 << endl;
	cout << "erase前str2:" << str2 << endl;
	//删除pos位置包括pos位置的后size个字符,删除位置也可以是一段迭代器区间
	str1.erase(pos, size);
	str2.erase(str2.begin()+5,str2.begin()+5+3);
	cout << "erase后str1:" << str1 << endl;
	cout << "erase后str2:" << str2 << endl;

	return 0;
}

Notice:

  • If the number of deletions given is greater than the number of characters behind the string, all the following characters will be deleted.
  • If you do not give the default parameter to delete the position setting, delete from 0.
  • If the number of deletions is not given, the number of deletions set by the default parameter is size_t npos = -1, about 4.2 billion.
  • After deletion, the length of the string will change, but the capacity will not change.

6.swap()

The swap exchange function is very simple in terms of non-function, so I won't introduce it much. But there is also a swap in std , let's compare the two swaps.

The bottom layer of std::swap() is implemented by using a function template. Not only the string type can be exchanged, but any modifiable type can be exchanged.

The principle is similar:


template<class T>
void Swap(T& e1,T& e2)
{
	T tmp = e1;
	e1 = e2;
	e2 = tmp;
}

The bottom layer of string::swap() is implemented by exchanging the string pointers in the string, and the overall efficiency is much higher than that of std::swap().

(6) String correlation algorithm

1.c_str()

Returns a C-style string.

 2.find()

Searches a string for the first occurrence of the sequence specified by its argument.
When pos is specified, the search includes only characters at or after position pos, ignoring any characters that may occur before position pos.

 For example:

int main()
{

	string str = "this is a string";
    //从1位置开始查找字符a,并返回位置。
	size_t pos = str.find('a', 1);
	cout << "a 在" << pos << "位置" << endl;

    return 0;
}

 Notice:

  • If no search position is given, the search starts from the default position 0.
  • If not found, size_t npos = -1 will be returned.

3.substr()

Returns a newly constructed String object whose value is initialized to a copy of a substring of this object.
A substring is the part of the object starting at character position pos and spanning len characters (or until the end of the string, whichever comes first).

example:

int main()
{

	int pos = 0;
	int length = 4;
	string str = "this is a string";
	//返回一个从pos位置开始,跨越长度为4的子串。
	string Substr = str.substr(0, 4);

	cout << "Substr:" << Substr << endl;

    return 0;
}

 Notice:

If no starting position is given, the default parameter is set to 0.

If no span length is given, the default argument is set to size_t npos = -1.

(7) Non-member function overloading

1.getline()

 Extract characters from is and store them into str until the delimiting character delim is found. When there is no delim, the default is ' \n ' as the delimiter.

 example:

int main()
{
	string str;
	cout << "输入:";
	std::getline(cin, str,'a');
	cout << "str:" << str << endl;

	return 0;
}

Guess you like

Origin blog.csdn.net/qq_63943454/article/details/129170049
Recommended