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的末尾