核心:
append——string类
push_back——vector数组
1、在字符串上,只有单个字符的添加,不可以用append,其余都可以
append
append()函数:是向string 的后面追加字符或字符串。
1、在字符串(str、char*)的末尾添加字符串str。
string s1="hello";
string s2= "a";//字符串不分长短,一个字母也是
string s3="world";
s1.append(s2); //把字符串s连接到当前字符串的结尾
s1+=s3;//和append同理
char c1 = 'b';
//s2.append(c1) 不可以加字符(单个、多个都不行,只要没加/0都是字符),会乱码
s1="hello a";
s1="hello a 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、字符串截取
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、字符数组
#include <iostream>
#include <string>
using namespace std;
void appendDemo(string str)
{
char ch1[6] = { 'G', 'e', 'e', 'k', 's', '\0' };
char ch2[] = { 'G', 'e', 'e', 'k', 's' };
char ch3[] = { 's' };
str.append(ch1);
string str1 = "asd";
str1.append(ch2);//添加单个字符会导致乱码
cout << str << endl<< str1 << endl;
}
int main()
{
string str("World");
string str1 = "asd";//两种方式都可以初始化string
cout << str1 << endl << str2 << endl << endl;
appendDemo(str);
system("pause");
return 0;
}
a
ab
aGeeks
asdGeeks烫烫烫烫烫蘂eeks
请按任意键继续. . .