Skip to content

Wiki

string container

About 11 min read

Existing English translations were reused. 2 current source blocks remain in Simplified Chinese, without triggering paid translation.

1.string container

1.1.basic concepts of string

Essence:

  • string is a string in the style of C++, while string is essentially a class

Difference between string and char *:

  • char * is a pointer
  • string is a class; the class internally encapsulates char*, manages this string, and is a container of type char*.

Features:

The string class encapsulates many member methods internally.

For example: find for search, copy for copy, delete for delete, replace for replace, insert for insert

string manages the memory allocated by char*, so there is no need to worry about copy out-of-bounds or access out-of-bounds; this is handled internally by the class.

1.2.string constructor

Constructor prototype:

  • string(); // Create an empty string, for example: string str; string(const char* s); // Initialize with string s
  • string(const string& str); // Initialize one string object with another string object
  • string(int n, char c); // Initialize with n characters c

Example:

#include <iostream>
#include <string>

using namespace std;

//string构造
void test01()
{
	string s1; //创建空字符串,调用无参构造函数
	cout << "str1 = " << s1 << endl;

	const char* str = "hello world";
	string s2(str); //把c_string转换成了string

	cout << "str2 = " << s2 << endl;

	string s3(s2); //调用拷贝构造函数
	cout << "str3 = " << s3 << endl;

	string s4(10, 'a');
	cout << "str3 = " << s3 << endl;
}

int main() {

	test01();


	return 0;
}

Operation result:

str1 =
str2 = hello world
str3 = hello world
str3 = hello world

Summary: The multiple constructors of string are not comparable; just use them flexibly.

1.3.string assignment operation

Function Description:

  • Assign a value to the string variable

Function prototype for assignment:

  • string& operator=(const char* s); //Assign a char* type string to the current string
  • string& operator=(const string &s); //Assign the string s to the current string
  • string& operator=(char c); //Assign a character to the current string
  • string& assign(const char *s); //Assign the string s to the current string
  • string& assign(const char *s, int n); //Assign the first n characters of the string s to the current string
  • string& assign(const string &s); //Assign the string s to the current string
  • string& assign(int n, char c); //Assign n copies of character c to the current string

Example:

#include <iostream>

using namespace std;

//赋值
void test01()
{
	string str1;
	str1 = "hello world";
	cout << "str1 = " << str1 << endl;

	string str2;
	str2 = str1;
	cout << "str2 = " << str2 << endl;

	string str3;
	str3 = 'a';
	cout << "str3 = " << str3 << endl;

	string str4;
	str4.assign("hello c++");
	cout << "str4 = " << str4 << endl;

	string str5;
	str5.assign("hello c++",5);
	cout << "str5 = " << str5 << endl;

	string str6;
	str6.assign(str5);
	cout << "str6 = " << str6 << endl;

	string str7;
	str7.assign(5, 'x');
	cout << "str7 = " << str7 << endl;
}

int main() {

	test01();


	return 0;
}

Operation result:

str1 = hello world
str2 = hello world
str3 = a
str4 = hello c++
str5 = hello
str6 = hello
str7 = xxxxx

Summary:

​ There are many ways to assign a value to a string,operator= this method is relatively practical.

1.4.string concatenation

Function description:

  • Implement concatenating a string at the end of a string

Function prototype:

  • string& operator+=(const char* str); // Overload the += operator
  • string& operator+=(const char c); // Overload the += operator
  • string& operator+=(const string& str); // Overload the += operator
  • string& append(const char *s); // Append string s to the end of the current string
  • string& append(const char *s, int n); // Append the first n characters of string s to the end of the current string
  • string& append(const string &s); // Same as operator+=(const string& str)
  • string& append(const string &s, int pos, int n);// Append n characters of string s starting from pos to the end of the string

Example:

#include <iostream>

using namespace std;

//字符串拼接
void test01()
{
	string str1 = "我";

	str1 += "爱玩游戏";

	cout << "str1 = " << str1 << endl;
	
	str1 += ':';

	cout << "str1 = " << str1 << endl;

	string str2 = "LOL DNF";

	str1 += str2;

	cout << "str1 = " << str1 << endl;

	string str3 = "I";
	str3.append(" love ");
	str3.append("game abcde", 4);
	//str3.append(str2);
	str3.append(str2, 4, 3); // 从下标4位置开始 ,截取3个字符,拼接到字符串末尾
	cout << "str3 = " << str3 << endl;
}
int main() {

	test01();


	return 0;
}

Operation result:

str1 = 我爱玩游戏
str1 = 我爱玩游戏:
str1 = 我爱玩游戏:LOL DNF
str3 = I love gameDNF

Summary: There are many overloaded versions of string concatenation; at the beginner stage, it is enough to remember just a few.

1.5.string search and replace

Function description:

  • Find: Find whether the specified string exists
  • Replace: Replace the string at the specified position

Function prototype:

  • int find(const string& str, int pos = 0) const; //Find the first occurrence of str, starting from pos
  • int find(const char* s, int pos = 0) const; //Find the first occurrence of s, starting from pos
  • int find(const char* s, int pos, int n) const; //Find the first occurrence of the first n characters of s, starting from pos
  • int find(const char c, int pos = 0) const; //Find the first occurrence of character c
  • int rfind(const string& str, int pos = npos) const; //Find the last occurrence of str, starting from pos
  • int rfind(const char* s, int pos = npos) const; //Find the last occurrence of s, starting from pos
  • int rfind(const char* s, int pos, int n) const; //Find the last occurrence of the first n characters of s, starting from pos
  • int rfind(const char c, int pos = 0) const; //Find the last occurrence of character c
  • string& replace(int pos, int n, const string& str); //Replace n characters starting from pos with string str
  • string& replace(int pos, int n,const char* s); //Replace n characters starting from pos with string s

Example:

#include <iostream>

using namespace std;

//查找和替换
void test01()
{
	//查找
	string str1 = "abcdefgde";

	int pos = str1.find("de");

	if (pos == -1)
	{
		cout << "未找到" << endl;
	}
	else
	{
		cout << "pos = " << pos << endl;
	}
	

	pos = str1.rfind("de");

	cout << "pos = " << pos << endl;

}

void test02()
{
	//替换
	string str1 = "abcdefgde";
	str1.replace(1, 3, "1111");

	cout << "str1 = " << str1 << endl;
}

int main() {

	//test01();
	//test02();


	return 0;
}

Run result: The program ended normally, with no output in the terminal.

Summary:

  • find searches from left to right, while rfind searches from right to left.
  • After find locates the string, it returns the position of the first character found; if not found, it returns -1.
  • When replacing, replace must specify from which position to start, how many characters to replace, and what string to replace them with.

1.6.string string comparison

Function description:

  • Comparison between strings

Comparison method:

  • String comparison is performed by comparing the ASCII codes of the characters.

= Return 0

\> Return 1

< Back -1

Function prototype:

  • int compare(const string &s) const; // Compare with string s
  • int compare(const char *s) const; // Compare with string s

Example:

#include <iostream>

using namespace std;

//字符串比较
void test01()
{

	string s1 = "hello";
	string s2 = "aello";

	int ret = s1.compare(s2);

	if (ret == 0) {
		cout << "s1 等于 s2" << endl;
	}
	else if (ret > 0)
	{
		cout << "s1 大于 s2" << endl;
	}
	else
	{
		cout << "s1 小于 s2" << endl;
	}

}

int main() {

	test01();


	return 0;
}

Operation result:

s1 大于 s2

Summary: String comparison is mainly used to compare whether two strings are equal; determining which is greater or smaller is not very meaningful.

1.7.string character access

There are two ways to access individual characters in a string.

  • char& operator[](int n); //通过[]方式取字符
  • char& at(int n); //通过at方法获取字符

Example:

#include <iostream>

using namespace std;

void test01()
{
	string str = "hello world";

	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) << " ";
	}
	cout << endl;

	//字符修改
	str[0] = 'x';
	str.at(1) = 'x';
	cout << str << endl;
	
}

int main() {

	test01();


	return 0;
}

Operation result:

h e l l o   w o r l d
h e l l o   w o r l d
xxllo world

总结:string字符串中单个字符存取有两种方式,利用 [ ] 或 at

1.8.string insertion and deletion

Function description:

  • Perform character insertion and deletion operations on a string.

Function prototype:

  • string& insert(int pos, const char* s); // Insert string
  • string& insert(int pos, const string& str); // Insert string
  • string& insert(int pos, int n, char c); // Insert n characters c at the specified position
  • string& erase(int pos, int n = npos); // Delete n characters starting from Pos

Example:

#include <iostream>

using namespace std;

//字符串插入和删除
void test01()
{
	string str = "hello";
	str.insert(1, "111");
	cout << str << endl;

	str.erase(1, 3);  //从1号位置开始3个字符
	cout << str << endl;
}

int main() {

	test01();


	return 0;
}

Operation result:

h111ello
hello

**Summary:** The starting indices for insertion and deletion both begin at 0

1.9.string substring

Function description:

  • Get the desired substring from a string

Function prototype:

  • string substr(int pos = 0, int n = npos) const; // Return a string consisting of n characters starting from pos

Example:

#include <iostream>

using namespace std;

//子串
void test01()
{

	string str = "abcdefg";
	string subStr = str.substr(1, 3);
	cout << "subStr = " << subStr << endl;

	string email = "hello@sina.com";
	int pos = email.find("@");
	string username = email.substr(0, pos);
	cout << "username: " << username << endl;

}

int main() {

	test01();


	return 0;
}

Operation result:

subStr = bcd
username: hello

**Summary:** Flexible use of the substring function allows effective information to be obtained in actual development.