Usage of append and push_back on strings

core:

1. In the string, only a single character can be added, append is not allowed, the rest can be used

Insert picture description here

append

append() function: is to append characters or strings to the back of string.

1. Add the string str at the end of the string (str, char ). *

string s1="hello";
string s2= "the";
string s3="world";
s1.append(s2);  //把字符串s连接到当前字符串的结尾
s1+=s3;
s1="hello the";
s1="hello the world";

The char* type is the form of passing strings in the string class, and it can save space

string str = "hello";
const char *c = "大家好!";
//char *c = "大家好!";
//char *c = "jiangkaiwen!";//都是要加const,无论是文字还是字母
str.append(c);
cout << str << endl;

string str_1 = "hello";
string str_2 = "hello";
string str_3 = "姜凯文";

str_1.append(str_2);
str_2.append(str_3);

cout << str_1 << endl;
cout << str_2 << endl;

Output:

hello大家好!
hellohello
hello姜凯文
请按任意键继续. . .

string to char *
data() does not append the terminator'\0' except for returning the content of the string

string str = "hello";
const char* p = str.data();

Char* to string
can be directly assigned

string s;
char *p = "hello";
s = p;

2. Add a substring of the string str at the end of the string

string s1 = "hello";
string s2 = "the world";
s1.append(s2,4,5);  //把字符串从s2中从4(从0开始算的4)开始的5个字符(算空格)连接到当前字符串的结尾
s1 = "hello world";//从空格开始
string s1 = "hello";
string s2 = "the world";
s1.append(s2, 3);//从0开始的
运行结果为:s1="hello world"

3. Character array

**// CPP code for comparison on the basis of 
// Appending character array 

#include <iostream> 
#include <string> 
using namespace std;

// Function to demonstrate comparison among 
// +=, append(), push_back() 
void appendDemo(string str)
{
    
    
	char ch[6] = {
    
     'G', 'e', 'e', 'k', 's', '\0' };
	string str1 = str;

	// Appending using += 
	str += ch;
	cout << "Using += : " << str << endl;

	// Appending using append() 
	str1.append(ch);
	cout << "Using append() : ";
	cout << str1 << endl;
}

// Driver code 
int main()
{
    
    
	string str("World of ");

	cout << "Original String : " << str << endl;
	appendDemo(str);

	system("pause");
	return 0;
}
Original String : World of
Using += : World of Geeks
Using append() : World of Geeks
请按任意键继续. . .

Guess you like

Origin blog.csdn.net/qq_43641765/article/details/111328083