C++中substr函数的用法

1 substr函数

/**
*  @brief  Get a substring.
*  @param __pos  Index of first character (default 0).
*  @param __n  Number of characters in substring (default remainder).
*  @return  The new string.
*  @throw  std::out_of_range  If __pos > size().
*
*  Construct and return a new string using the @a __n
*  characters starting at @a __pos.  If the string is too
*  short, use the remainder of the characters.  If @a __pos is
*  beyond the end of the string, out_of_range is thrown.
*/
basic_string
substr(size_type __pos = 0, size_type __n = npos) const
{ return basic_string(*this,
	    _M_check(__pos, "basic_string::substr"), __n); }

1 用法

1.1 例1

程序:

#include<string>
#include<iostream>
using namespace std;
int main()
{
  string s("12345asdf");
  string a = s.substr(0, 5);     //获得字符串s中从第0位开始的长度为5的字符串
  cout << a << endl;
}

输出结果:

12345

1.2 例2

程序:

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3, 5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

输出:

think live in details.

2 小结

  • 用途:一种构造string的方法
  • 形式s.substr(pos, n)
  • 解释:返回一个string,包含s中从pos开始的n个字符的拷贝(pos的默认值是0,n的默认值是s.size() - pos,即不加参数会默认拷贝整个s)
  • 补充:若pos的值超过了string的大小,则substr函数会抛出一个out_of_range异常;若pos+n的值超过了string的大小,则substr会调整n的值,只拷贝到string的末尾
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值