[C++ Elementary] Part VII: Basic interface usage of string

Commonly used interface descriptions of the string class (only the most commonly used interfaces are explained)

First, the common structure of string class objects

The string class implements the overloading of multiple constructors, and the commonly used constructors are as follows:

function name Function Description
string() constructs an empty string
string(const char * s) Use strings to construct string objects
string (const string& str) copy constructor
string(size_t n, char c) Use n characters c to construct a string object
string(const char * s, size_t n) Copies the first n characters from the character array pointed to by s
string(const string& str, size_t pos, size_t len = npos) Copy the portion of str starting at character position pos and spanning len characters

Example usage:

string s1;                     //构造空字符串
string s2("hello string");     //用"hello string"字符串来构造string对象 
string s3(s2);                 //拷贝构造
string s4 = "hello string"		//也是拷贝构造 --- string支持赋值运算符重载
string s5(10, 's');            //生成10个's'字符的字符串
string s6("hello string", 3);  //复制"hello string"的前3个字符给s5
string s7(s2, 0, 4);           //复制s2中从字符位置0开始并跨越4个字符的部分

2. Access and traversal operations of string class objects

function name Function Description
operator[ ] (emphasis) Returns the character at position pos
Forward iterator: begin + end (emphasis) begin gets an iterator for a character + end gets an iterator for the next position of the last character
Reverse iterator: rbegin + rend begin gets an iterator for a character + end gets an iterator for the next position of the last character
range for (emphasis) C++11 supports a new traversal method for a more concise range for

Example usage:

1. operator[ ]: Overloading the [ ] operator

void test_string1()
{
    
    
	string s1("1234");
	// 遍历
	// 1、下标 []
	for (size_t i = 0; i < s1.size(); ++i)
	{
    
    
		s1[i]++;
	}
	cout << s1 << endl;
}

2. Range for:

void test_string2()
{
    
    
	string s1("1234");
	// 2、范围for
	for (auto& ch : s1)
	{
    
    
		ch++;//每个字符加加
	}

	for (auto e : s1)
	{
    
    
		cout << e ;//遍历打印
	}
	cout << endl;
	//cout << s1 << endl;//也可以直接打印,
}

Ordinary loop traversal:

void test_string2()
{
    
    
	string s1("1234");
	// 反转一下
	size_t begin = 0, end = s1.size() - 1;//size()计算字符串有效字符个数
	while (begin < end)
	{
    
    
		swap(s1[begin++], s1[end--]);
	}
	cout << s1 << endl;

}

3. Iterators:

1. The function related to the forward iterator
begin function: returns an iterator pointing to the first character of the string.
insert image description here

Function prototype:
    iterator begin();
 const_iterator begin() const;

end function: Returns an iterator pointing to the end character of the string, ie '\0'.
insert image description here

Function prototype:
    iterator end();
 const_iterator end() const;

Example usage:

void test_string3()
{
    
    
	string s1("1234");
	//正向迭代器 --- 关键字:iterator
	string::iterator it1 = s1.begin();
	while (it1 != s1.end())
	{
    
    
		//每个字符加1
		*it1 += 1;
		++it1;
	}

	it1 = s1.begin();
	while (it1 != s1.end())
	{
    
    
		//遍历打印
		cout << *it1 << " ";
		++it1;
	}
	//2 3 4 5
	cout << endl;
}

Note: bigin() and end() for forward iterators should appear together!

2. The function related to the reverse iterator
rbegin function: returns the reverse iterator pointing to the last character of the string.
insert image description here

Function prototype:
    reverse_iterator rbegin();
 const_reverse_iterator rbegin() const;

rend function: Returns a reverse iterator pointing to the theoretical element preceding the first character of the string.
insert image description here

Function prototype:
    reverse_iterator rbegin();
 const_reverse_iterator rbegin() const;

Example usage:

void test_string3()
{
    
    
	string s1("1234");
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
    
    
		//每个字符加1
		cout << *it << " ";
		++it;
	}
	cout << endl;
	
	//反向迭代器 --- 关键字:reverse_iterator
	string::reverse_iterator rit = s1.rbegin();
	//若觉得类型过长,书写麻烦,我们可以使用auto自动推导类型
	//auto rit = s1.rbegin();可自动推到类型
	while (rit != s1.rend())
	{
    
    
		//反向遍历
		cout << *rit << " ";
		++rit;
	}
	//5 4 3 2
	cout << endl;
}

Note: rbigin() and rend() for reverse iterators should appear together!

const iterator:
The above demonstration is only non-const iterator, we can read and write strings, and const iterator only allows us to read.

insert image description here
To sum up, we can make a summary of the iterator table:

Iterators (both can be deduced with auto) non-const const
Forward (forward) readable and writable (iterator)begin(),end() (forward) readable but not writable (const_iterator)begin(),end()
reverse (reverse) readable and writable (reverse_iterator) rbegin(), rend() (reverse) readable and writable (const_reverse_iterator) rbegin(), rend()

4. Use at to access the elements in the object
Because the at function is also used to return the reference, we can also modify the element at the corresponding position through the at function.
insert image description here

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s("CSDN");
	for (size_t i = 0; i < s.size(); i++)
	{
    
    
		//at(pos)访问pos位置的元素
		cout << s.at(i);
	}
	cout << endl;

	for (size_t i = 0; i < s.size(); i++)
	{
    
    
		//at(pos)访问pos位置的元素,并对其进行修改
		s.at(i) = 'x';
	}
	cout << s << endl; //xxxx
	return 0;
}

3. Capacity operation of string objects

insert image description here

insert image description here

1. Use the size function or length function to obtain the number of currently valid characters

insert image description here

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s("CSDN");
	cout << s.size() << endl; //4
	cout << s.length() << endl; //4
	return 0;
}

2. Use the capacity function to obtain the size of the storage space allocated by the current object

insert image description here

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s("CSDN");
	cout << s.capacity() << endl; //15
	return 0;
}

3. Use the max_size function to obtain the maximum number of characters that a string object can contain

insert image description here

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s("CSDN");
	cout << s.max_size() << endl; //4294967294
	return 0;
}

4. Use clear to clear the contents of the object, and the object becomes an empty string after deletion

insert image description here

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s("CSDN");

	//clear()删除对象的内容,该对象将变为空字符串
	s.clear();
	cout << s << endl; //空字符串
	return 0;
}

5. Use empty to judge whether the object is empty,
return true if it is empty, and return false if it is not empty

insert image description here

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s("CSDN");
	cout << s.empty() << endl; //0

	//clear()删除对象的内容,该对象将变为空字符串
	s.clear();
	cout << s.empty() << endl; //1
	return 0;
}

6. Resize function

insert image description here
rule:

resize(n)
n<size If n is less than the current string length, the current value is shortened to the nth character, characters beyond the nth character are removed.
size<n<capacity If n is greater than size and less than capacity, there will be no expansion, and the space will be greater than size. If the specified character c is given, it will be filled with c. If c is not given, it will default to '\0'.
n>capacity For string expansion, if the given n is greater than the current capacity of the object, the capacity will also be expanded according to its own growth rules.

insert image description here

7. Use reserve to change the capacity of the current object
insert image description here

Reserve rules:
 1. When n is greater than the current capacity of the object, expand the capacity to n or greater than n.
 2. When n is less than the current capacity of the object, do nothing.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s("CSDN");
	cout << s << endl; //CSDN
	cout << s.size() << endl; //4
	cout << s.capacity() << endl; //15

	//reverse(n)当n大于对象当前的capacity时,将当前对象的capacity扩大为n或大于n
	s.reserve(20); 
	cout << s << endl; //CDSN
	cout << s.size() << endl; //4
	cout << s.capacity() << endl; //31

	//reverse(n)当n小于对象当前的capacity时,什么也不做
	s.reserve(2);
	cout << s << endl; //CDSN
	cout << s.size() << endl; //4
	cout << s.capacity() << endl; //31
	return 0;
}

Note: This function has no effect on the size of the string, and its contents cannot be changed.

8. Function of shrink_to_fit
insert image description here

Fourth, the modification operation of the string class object

1. push_back:
  Insert a character at the end

void test_string()
{
    
    
	string s1("hello world");
	s1.push_back(' ');
	s1.push_back('!');
	cout << s1 << endl;//hello world !
}

2. append:
  Append a string after the string
  Commonly used parameter passing methods:

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

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s1("I");
	string s2(" like");

	//append(string)完成两个string对象的拼接
	s1.append(s2); //I like

	//append(str)完成string对象和字符串str的拼接
	s1.append(" C++"); //I like C++

	//append(n, char)将n个字符char拼接到string对象后面
	s1.append(3, '!'); //I like C++!!!
	
	cout << s1 << endl; //I like C++!!!
	return 0;
}

3. operator+= (emphasis): The
  += operator is overloaded in the string class, and the overloaded += operator supports the compound assignment of the string class, the compound assignment of strings and the compound assignment of characters
insert image description here

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s1;
	string s2("hello");

	//支持string类的复合赋值
	s1 += s2;
	cout << s1 << endl; //hello

	//支持字符串的复合赋值
	s1 += " CSDN";
	cout << s1 << endl; //hello CSDN

	//支持字符的复合赋值
	s1 += '!';
	cout << s1 << endl; //hello CSDN!
	return 0;
}

4. insert: Insert the common parameter passing method
  at pos position :
  

string& insert (size_t pos, const string& str);
string& insert (size_t pos, const char* s);
iterator insert (iterator p, char c);

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s("C"); //C

	//insert(pos, str)在pos位置插入字符串str
	s.insert(1, "S"); //CS

	//insert(pos, string)在pos位置插入string对象
	string t("D");
	s.insert(2, t); //CSD

	//insert(pos, char)在pos位置插入字符char
	s.insert(s.end(), 'N'); //CSDN
	
	cout << s << endl; //CSDN
	return 0;
}

5. erase: delete the common parameter passing method
  at the position of pos :
  

string& erase (size_t pos = 0, size_t len ​​= npos);//Delete len characters from pos position, if no len is passed, all characters at pos position and after will be deleted by default iterator erase (iterator p); iterator erase
(
iterator first, iterator last);

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s("I like C++!!!");

	//erase(pos, n)删除pos位置开始的n个字符
	s.erase(8, 5); //I like C
	cout << s << endl; //I like C

	//erase(pos)删除pos位置的字符
	s.erase(s.end() - 1); //I like
	cout << s << endl; //I like

	//erase(pos1, pos2)删除[pos1pos2)上所有字符
	s.erase(s.begin() + 1, s.end()); //I
	cout << s << endl; //I
	return 0;
}

6. assign:
  assign can be understood as clearing the original character object and performing the assignment operation again.
  Commonly used parameter passing methods:

string& assign (const string& str);
string& assign (const char* s);
string& assign (const char* s, size_t n);
string& assign (size_t n, char c);

void test_string()
{
    
    
	string s1("hello world hello world");
	string s2("CSDN");

	//将s1清空,替换指定string对象
	s1.assign(s2);
	cout << s1 << endl;//CSDN

	//将s1清空,替换指定字符串
	s1.assign("hello C++");
	cout << s1 << endl;//hello C++

	//将s1清空,替换指定字符串的一部分
	s1.assign("hello C++", 5);
	cout << s1 << endl;//hello

	//将s1清空,替换n个指定的字符
	s1.assign(5, '!');
	cout << s1 << endl;//!!!!!
}

7. replace:
  replace is a partial replacement of character objects.
  Commonly used parameter passing methods:

string& replace (size_t pos, size_t len, const string& str);
string& replace (size_t pos, size_t len, const char* s);

void test_string()
{
    
    
	string s1("hello world hello world");
	string s2("CSDN");

	//从第六个下标位置开始,将五个字符替换成s2对象
	s1.replace(6, 5, s2);
	cout << s1 << endl;//hello CSDN hello world

	//从第六个下标位置开始,将五个字符替换成指定字符串
	s1.replace(6, 5, "C++");
	cout << s1 << endl;//hello C++hello world
}

8. find:
  Use the find function to search forward for the first matching item.
  Commonly used parameter passing methods:

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 (char c, size_t pos = 0) const;

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s1("http://www.cplusplus.com/reference/string/string/find/");

	//find(string)正向搜索与string对象所匹配的第一个位置
	string s2("www");
	size_t pos1 = s1.find(s2);
	cout << pos1 << endl; //7

	//find(str)正向搜索与字符串str所匹配的第一个位置
	char str[] = "cplusplus.com";
	size_t pos2 = s1.find(str);
	cout << pos2 << endl;  //11

	//find(char)正向搜索与字符char所匹配的第一个位置
	size_t pos3 = s1.find(':');
	cout << pos3 << endl; //4
	return 0;
}

9. rfind:
  Use the rfind function to search in reverse for the first match.
  Commonly used parameter passing methods:

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 (char c, size_t pos = npos) const;

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s1("http://www.cplusplus.com/reference/string/string/find/");

	//rfind(string)反向搜索与string对象所匹配的第一个位置
	string s2("string");
	size_t pos1 = s1.rfind(s2);
	cout << pos1 << endl; //42

	//rfind(str)反向搜索与字符串str所匹配的第一个位置
	char str[] = "reference";
	size_t pos2 = s1.rfind(str);
	cout << pos2 << endl;  //25

	//rfind(char)反向搜索与字符char所匹配的第一个位置
	size_t pos3 = s1.rfind('/');
	cout << pos3 << endl; //53
	return 0;
}

10. substr
  Use the substr function to extract the substring in the string

string substr (size_t pos = 0, size_t len ​​= npos) const;//Extract the len character sequence starting from pos position as the return value

Extract the suffix of the file

void test_string()
{
    
    
	// "Test.cpp"
	// "Test.cpp.tar"
	string file;
	cin >> file;
	// 要求取后缀
	//应该使用rfind,因为有些文件名可能有两个点
	size_t pos = file.rfind('.');
	if (pos != string::npos)
	{
    
    
		//string suffix = file.substr(pos, file.size() - pos);
		string suffix = file.substr(pos);//提取pos位置开始的len个字符序列作为返回值

		cout << suffix << endl;
	}
}

11.c_str
  gets the first address of the character array and traverses it in the form of C string

const char* c_str() const;

void TestString()
{
    
    
	//获取字符数组首地址,用C字符串的形式遍历
	string s1("hello world");
	const char* str = s1.c_str();
	while (*str)
	{
    
    
		cout << *str << " ";
		str++;
	}
	cout << endl;
	s1 += '\0';
	s1 += " hello";
	cout << s1 << endl;           //调用的string重载operator<<  将对象数组中所有字符都输出
	cout << s1.c_str() << endl;   //直接输出const char* 遇到\0结束
}

insert image description here
insert image description here

Five, string class non-member functions

insert image description here
1. operator+
The + operator is overloaded in the string class, and the overloaded + operator supports the following types of operations:
 string class + string class
 string class +
 string string + string class
 string class + character
 character + string class
They all return a string class object after being added.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s;
	string s1("hello");
	string s2("world");
	char str[] = "wyt";
	char ch = '!';

	//string类 + string类
	s = s1 + s2;
	cout << s << endl; //helloworld

	//string类 + 字符串
	s = s1 + str;
	cout << s << endl; //hellowyt

	//字符串 + string类
	s = str + s1;
	cout << s << endl; //wythello

	//string类 + 字符
	s = s1 + ch;
	cout << s << endl; //hello!
	
	//字符 + string类
	s = ch + s1;
	cout << s << endl; //!hello
	return 0;
}

2. operator>> and operator<<
The string class also overloads the >> and << operators, which is why we can directly use >> and << to input and output the string class.

istream& operator>> (istream& is, string& str);
ostream& operator<< (ostream& os, const string& str);

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s;
	cin >> s; //输入
	cout << s << endl; //输出
	return 0;
}

3.
A series of relational operators are also overloaded in the relational operators string class, which are ==, !=, <, <=, >, >=. The overloaded relational operators support the relational comparison between the string class and the string class, the relational comparison between the string class and the string, and the relational comparison between the string and the string class.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s1("abcd");
	string s2("abde");
	cout << (s1 > s2) << endl; //0
	cout << (s1 < s2) << endl; //1
	cout << (s1 == s2) << endl; //0
	return 0;
}

Note: These overloaded relational comparison operators compare the ASCII code values ​​​​of the corresponding characters.

4. Getline
We know that when using >> for input operations, when >> reads a space, it will stop reading. Based on this, we will not be able to use >> to read a string of strings containing spaces into the string object .

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s;
	cin >> s; //输入:hello CSDN
	cout << s << endl; //输出:hello
	return 0;
}

At this time, we need to use the getline function to complete the reading operation of a string of strings containing spaces.

Usage one:

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

The getline function stores the characters extracted from is into str until the newline character '\n' is read

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s;
	getline(cin, s); //输入:hello CSDN
	cout << s << endl; //输出:hello CSDN
	return 0;
}

Usage two:

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

The getline function stores the characters extracted from is into str until the delimiter delim or the newline character '\n' is read.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
	string s;
	getline(cin, s, 'D'); //输入:hello CSDN
	cout << s << endl; //输出:hello CS
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_58124165/article/details/129803689