【C++学习纪录】string容器——字符串的拼接

string字符串的拼接
1、string &operator+=(const char *str) 重载+=操作符
2、string &operator+=(const char c) 重载+=操作符
3、string &operator+=(const string &str) 重载+=操作符
4、string &append(const char *s) 把字符串s连接到当前字符串末尾
5、string &append(const char *s, int n) 把字符串s前n个字符连接到当前字符串末尾
6、string &append(const string &s) 同operator+=(const string &str)
7、string &append(const string &s, int pos, int n) 字符串s中从pos位置开始的n个字符连接到当前字符串的末尾

一、string &operator+=(const char *str) 重载+=操作符

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str("hello ");
    const char *s = "world";
    str += s;
    cout << str << endl;
    system("pause");
}

运行结果:

hello world
请按任意键继续. . .

二、string &operator+=(const char c) 重载+=操作符

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str("hello");
    char c = '!';
    str += c;
    cout << str << endl;
    system("pause");
}

运行结果:

hello!
请按任意键继续. . .

三、string &operator+=(const string &str) 重载+=操作符

四、string &append(const char *s) 把字符串s连接到当前字符串末尾

五、string &append(const char *s, int n) 把字符串s前n个字符连接到当前字符串末尾

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str("My name is ");
    //在这个函数里,后面接上的字符串只能来自char*类型字符串,
    //不可以来自string
    char *temp = "Joe is my name.";
    str.append(temp, 3);
    cout << str << endl;
    system("pause");
}

运行结果:

My name is Joe
请按任意键继续. . .

六、string &append(const string &s) 同operator+=(const string &str)

七、string &append(const string &s, int pos, int n) 字符串s中从pos位置开始的n个字符连接到当前字符串的末尾

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str("My name is ");
    string temp("Joe!");
    //注意,string类中首元素下标也为0
    //该函数中第三个参数应该是希望截取的字符串末尾下标+1,不是末尾下标本身
    //就是说这个函数会截取第三个参数之前到第二个参数之间的字符串
    //不包含第三个参数所指向下标的字符
    str.append(temp, 0, 4);//为了接上最后的感叹号字符,第三个参数是4而不是3
    cout << str << endl;
    system("pause");
}

运行结果:

My name is Joe!
请按任意键继续. . .
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值