《白话C++》第10章 Page49 10.3 字符串处理 求子串 字符串拼接

9.求子串

string substr(size_t pos = 0, size_t len = npos) const;

substr得到当前串从pos位置开始,长度为len范围内的子串,参数采用默认值则相当于复制原串。

10.字符串拼接

使用“+”可以方便实现拼接两个字符串:

string s1 = "Hello";
string s2 = "Tom";

string s3 = s1 + " " + s2 + "!";

不过,由于字符串不是内置类型,所以加号两端,必须至少有一个是std::string类型,不支持直接相加两个C风格字符串:

//不支持,因为相加过程和std::string无关
string s = "Hello" + "Tom!";

string s1 = string("Hello") + " Tom!";//支持
string s2 = "Hello" + string(" Tom!");//支持

自加操作“+=”也有意义直观的支持

string s3 = "Hello";
s3 += " Tom!";

使用+和+=拼接字符串,虽然方便,但效率不高,另外也不方便拼接其他类型,比如整数,更常用的方法是使用标准库的内存字符流std::stringstream

#include <sstream>

string s1 = "How";
string s2 = "old";
char const* s3 = "are";

int age = 9;

std::stringstream ss;
ss << s1 << ' ' << s2 << " " 
   << s3 << " you? I am " << age << '.';
string result = ss.str();
cout << result << endl;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值