C++编程思想 第2卷 第3章 深入理解字符串 对字符串进行操作 使用非成员重载运算符连接

C++string处理,借助operator+和operator+=可以如此轻而易举地实现
string的合并与追加

运算符使合并串的操作在语法上类似于数值型数据的加法运算

//: C03:AddStrings.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <string>
#include <cassert>
using namespace std;

int main() {
  string s1("This ");
  //        s1    "This "    std::basic_string<char,std::char_traits<char>,std::allocator<char> >

  string s2("That ");
  //          s2    "That "    std::basic_string<char,std::char_traits<char>,std::allocator<char> >

  string s3("The other ");
  //        s3    "The other "    std::basic_string<char,std::char_traits<char>,std::allocator<char> >

  // operator+ concatenates strings
  s1 = s1 + s2;
  //        s1    "This That "    std::basic_string<char,std::char_traits<char>,std::allocator<char> >

  assert(s1 == "This That ");
  //        返回 std::operator==<char,std::char_traits<char>,std::allocator<char> >    true    bool

  // Another way to concatenates strings
  s1 += s3;
  //        s1    "This That The other "    std::basic_string<char,std::char_traits<char>,std::allocator<char> >

  assert(s1 == "This That The other ");
  //        s1    "This That The other "    std::basic_string<char,std::char_traits<char>,std::allocator<char> >

  // You can index the string on the right
  s1 += s3 + s3[4] + "ooh lala";
  //        s1    "This That The other The other oooh lala"    std::basic_string<char,std::char_traits<char>,std::allocator<char> >

  assert(s1 == "This That The other The other oooh lala");
  //        返回 std::operator==<char,std::char_traits<char>,std::allocator<char> >    true    bool

} ///:~

没有弹出异常对话框,说明正确运行

operator+和operator+=运算符是合并string数据的一种即灵活又
方便的方法。
在语句的右边,程序员几乎可以采用任意一种样式对由单字符或多字符
构成的分组进行赋值
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值