C++中STL拼接字符串的方法

C++中STL拼接字符串的方法

要拼接字符串,可使用运算符+=,也可使用成员函数 append():

string sampleStr1 ("Hello");
string sampleStr2 (" String! ");
sampleStr1 += sampleStr2; // use std::string::operator+=
// alternatively use std::string::append()
sampleStr1.append (sampleStr2); // (overloaded for char* too)

下面函数的作用是 将 字符串 s 连接到 当前 string 类型字符串对象 的结尾 , char* 类型字符串 和 string 类型字符串都可 ;

// 返回的是本字符串 , 方便链式调用
string& operator+=(const string &s);  
string& operator+=(const char *s);

string& operator+=(const string &s); 函数原型 分析 : 该函数 是 string 类中用于重载 += 运算符的成员函数原型 ;

operator+= 函数的主要目的是将一个 string 对象追加到另一个 string 对象的末尾 , 并返回修改后的 string 对象的引用 ;

string& operator+=(const string &s); 函数返回一个对 string 对象的引用 , 这意味着当你使用这个运算符时 , 你实际上是在操作原始对象 , 而不是创建一个新的对象 ; 通过返回引用 , 可以实现链式操作 , 如 : str1 += str2 += str3 ;

代码示例 :

string s1 = "123456789";
string s2 = "abcdefghi";

// 使用 重载运算符 += 连接 s1 与 s2 字符串
s1 += s2;
cout << "s1 = " << s1 << endl;

// 使用 重载运算符 + 连接 s1 与 s2 字符串
s2 += "ABCD";
cout << "s2 = " << s2 << endl;

2、字符串重载函数 - operator+ 函数

operator+ 函数 是 string 类中的 成员函数 , 该函数接受一个 const string 类字符串 或 const char* 字符串 , 作为参数,返回一个新的 string 类型的值 ;

// 返回的是新字符串
string operator+(const string& s);  
string operator+(const char* s);

特别注意 : 该函数不能进行链式调用 ;

代码示例 :

string s1 = "123456789";
string s2 = "abcdefghi";

// 使用 重载运算符 + 连接 s1 与 s2 字符串
string s3 = s1 + s2;
cout << "s3 = " << s3 << endl;

// 使用 重载运算符 + 连接 s1 与 s2 字符串
string s4 = s2 + "EFG";
cout << "s4 = " << s4 << endl;

程序清单 16.3 演示了这两种方式。

0: #include <string>
1: #include <iostream>
2:
3: int main ()
4: {
5: using namespace std;
6:
7: string sampleStr1 ("Hello");
8: string sampleStr2 (" String!");
9:
10: // Concatenate
11: sampleStr1 += sampleStr2;
12: cout << sampleStr1 << endl << endl;
13:
14: string sampleStr3 (" Fun is not needing to use pointers!");
15: sampleStr1.append (sampleStr3);
16: cout << sampleStr1 << endl << endl;
17:
18: const char* constCStyleString = " You however still can!";
19: sampleStr1.append (constCStyleString);
20: cout << sampleStr1 << endl;
21:
22: return 0;
23: }

输出:

Hello String!
Hello String! Fun is not needing to use pointers!
Hello String! Fun is not needing to use pointers! You however still can!

分析:
第 11、 15 和 19 行演示了各种拼接 STL string 的方法。请注意运算符+=的用法以及 append 函数的
功能。 append 函数有多个重载版本,能够接受另一个 string 对象(如第 15 行所示),还能接受一个 C
风格字符串。

对C++编程技术感兴趣的朋友请点击这里:零声学院C/C++服务器课程

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值