substr()函数

substr

定义于头文件 <string>

string substr (size_t pos = 0, size_t len = npos) const;
复制子字符串,要求从指定位置开始,并具有指定的长度。
如果pos等于字符串长度,则返回一个空串,如果pos大于字符串长度,抛出异常。
如果len大于字符串长度,则返回[pos,size()]。

参数
pos - 从此位置开始复制
len - 复制 len 长度的字符串
返回值
返回字符串,包含[pos, len]
示例

// 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 << '
';

  return 0;
}

//think live in details.

  

原文地址:https://www.cnblogs.com/ZhaoxiCheung/p/6222496.html