Basic usage of C++ string type

Table of contents

1. Define and initialize the string object

2. Common operations on string objects

In C++, string is used to process variable-length strings. It is a type provided in the C++ standard library, and it is very convenient to use. At the same time, C++ also supports character arrays in C language to represent strings. Remember to include the string header file when using it.

1. Define and initialize the string object:

The following is a comparison with the C language:

	char arr1[] = "csdn";//C语言
	string arr2 = "csdn";//C++
	printf("%s\n", arr1);
	cout << arr2 << endl;

Add some other definition and initialization methods:

	string s1;//默认初始化,s1代表一个空串
	string s2("csdn");//与string s2 = “csdn”;等价
	int num = 5;
	string s3(num, 'a');//初始化一个连续num个字符‘a’组成的字符串

There is also copy initialization, which will be discussed below.

2. Common operations on string objects:

(1) Determine whether it is empty () and return a Boolean value.

	string s1;
	if (s1.empty())//为空成立
	{
		cout<<"s1为空字符串" << endl;
	}

(2) size()/length() returns the number of bytes/characters, which can be understood as returning an unsigned unsigned int.

	string s1;
	cout << s1.size() << " " << s1.length() << endl;//0 0
	string s2 = "csdn";
	cout << s2.size() << " " << s2.length() << endl;//4 4

(3) s1[n]: similar to the character array of C language, return the nth character in s1, the character position starts from zero, pay attention to the length of the string and do not access it out of bounds .

	string s2 = "csdn";
	cout << s2.size() << " " << s2.length() << endl;//4 4
	cout << s2[0] << " " << s2[1] << " " << s2[2] << endl;

(4) s1 + s2: string concatenation operation:

Note: A string constant + string object is allowed here

	string s1 = "cs";
	string s2 = "dn";
	string s3 = s1 + s2;
	cout << s1 + s2 << " " << s3 << endl;//csdn csdn
	cout << s1 + "dn" << " " << "cs" + s2 << endl;//csdn csdn
	//不允许“cs”+“dn”+s1但可以“cs”+s1+“dn”

(5) String assignment operation: s1 = s2 copies the content of s2 to replace the content of s1.

	string s1 = "cs";
	string s2 = "dn";
	string s3 = s1;//cs
	string s4 = s2;//dn
	cout << s3 + s4 << endl;//csdn

(6) Determine whether the two strings are equal (the length and case must be the same to be equal) .

	string s1 = "csdn";
	string s2 = "csdn";
	if (s1 == s2) {
		cout << "s1==s2" << endl;
	}

(7) Read and write string objects:

	string s1;
	cin >> s1;
	cout << s1 << endl;

There is also an input function getline(cin, s1) that takes in strings with spaces

In fact, there are many operation functions for strings, here are just some simple uses.

Thank you for watching, thank you for your attention~

Guess you like

Origin blog.csdn.net/m0_74358683/article/details/131654902