append和push_back在字符串上的用法

核心:

1、在字符串上,只有单个字符的添加,不可以用append,其余都可以

在这里插入图片描述

append

append()函数:是向string 的后面追加字符或字符串。

1、在字符串(str、char)的末尾添加字符串str。*

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

char*类型是string类传递字符串的形式,而且可以节省空间

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;

输出:

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

string转char*
data()除了返回字符串内容外,不附加结束符’\0’

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

char*转string
可以直接赋值

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

2、符串的末尾添加字符串str的子串

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、字符数组

**// 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
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/qq_43641765/article/details/111328083