一、介绍
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
形式 : str.substr(pos, len)
返回值: string,包含str中从pos开始的len个字符的拷贝(pos的默认值是0,len的默认值是s.size() - pos,即如果不加参数,会默认拷贝整个str)
异常 :若pos的值超过了string的大小,则substr函数会抛出一个out_of_range异常;若pos+n的值超过了string的大小,则substr会调整n的值,只拷贝到string的末尾
//substr有2种常用用法:
//假设:string s = “0123456789”;
string sub1 = s.substr(5); //只有一个数字5表示从下标为5开始一直到结尾:sub1 = “56789”
string sub2 = s.substr(5, 3); //从下标为5开始截取长度为3位:sub2 = “567”
二、分割字符串
使用
//字符串分割函数
std::vector<std::string> split(std::string str, std::string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
str += pattern;//扩展字符串以方便操作
int size = str.size();
for (int i = 0; i < size; i++)
{
pos = str.find(pattern, i);
if (pos < size)
{
std::string s = str.substr(i, pos - i);
result.push_back(s);
i = pos + pattern.size() - 1;
}
}
return result;
}
int main()
{
std::string str;
std::cout << "Please input str:" << std::endl;
std::cin >> str; // 输入字符串
std::string pattern;
std::cout << "Please input pattern:" << std::endl;
std::cin >> pattern; // 分割符
std::vector<std::string> result = split(str, pattern);
std::cout << "The result:" << std::endl;
for (int i = 0; i < result.size(); i++)
{
std::cout << result[i] << std::endl; // 打印
}
system("pause");
return 0;
}
输出
参考: