C++中substr函数的用法

原地址:https://www.cnblogs.com/xzxl/p/7243490.html

1

2

3

4

5

6

7

8

9

#include

#include

using namespace std;

int main()

{

  string s("12345asdf");

  string a = s.substr(0,5);     //获得字符串s中从第0位开始的长度为5的字符串

  cout << a << endl;

}

输出结果为:12345

 

【更多】

0. 用途:一种构造string的方法

1. 形式:s.substr(pos, n)

2. 解释:返回一个string,包含s中从pos开始的n个字符的拷贝(pos的默认值是0,n的默认值是s.size() - pos,即不加参数会默认拷贝整个s)

3. 补充:若pos的值超过了string的大小,则substr函数会抛出一个out_of_range异常;若pos+n的值超过了string的大小,则substr会调整n的值,只拷贝到string的末尾

你可能感兴趣的:(c++)