跳到主要内容

std::string substr() 方法

// Const version only
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const;

返回子字符串 [ pos, pos + count )
如果请求的子字符串超出字符串的末尾,即 count 大于 size() - pos (例如,如果 count == npos),则返回的子字符串是 [ pos, size() )

参数

  • pos - 要包含的第一个字符的位置
  • count - 子字符串的长度

返回值

包含子字符串 [ pos, pos + count )[ pos, size() ) 的字符串。

复杂度

线性于 count - O(count)

异常

如果 pos > size(),则抛出 std::out_of_range

备注

返回的字符串的构造方式如同 basic_string(data() + pos, count),这意味着返回的字符串的分配器将被默认构造——新的分配器可能不是get_allocator()的副本。

示例

#include <string>
#include <iostream>

int main()
{
std::string a = "0123456789abcdefghij";

// count is npos, returns [pos, size())
std::string sub1 = a.substr(10);
std::cout << sub1 << '\n';

// both pos and pos+count are within bounds, returns [pos, pos+count)
std::string sub2 = a.substr(5, 3);
std::cout << sub2 << '\n';

// pos is within bounds, pos+count is not, returns [pos, size())
std::string sub4 = a.substr(a.size()-3, 50);
// this is effectively equivalent to
// std::string sub4 = a.substr(17, 3);
// since a.size() == 20, pos == a.size()-3 == 17, and a.size()-pos == 3

std::cout << sub4 << '\n';

try {
// pos is out of bounds, throws
std::string sub5 = a.substr(a.size()+3, 50);
std::cout << sub5 << '\n';
} catch(const std::out_of_range& e) {
std::cout << "pos exceeds string size\n";
}
}
输出
abcdefghij
567
hij
pos exceeds string size
本文源自此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了修改。点击“编辑此页面”查看本文档所做的所有更改。
悬停查看原始许可证。

std::string substr() 方法

// Const version only
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const;

返回子字符串 [ pos, pos + count )
如果请求的子字符串超出字符串的末尾,即 count 大于 size() - pos (例如,如果 count == npos),则返回的子字符串是 [ pos, size() )

参数

  • pos - 要包含的第一个字符的位置
  • count - 子字符串的长度

返回值

包含子字符串 [ pos, pos + count )[ pos, size() ) 的字符串。

复杂度

线性于 count - O(count)

异常

如果 pos > size(),则抛出 std::out_of_range

备注

返回的字符串的构造方式如同 basic_string(data() + pos, count),这意味着返回的字符串的分配器将被默认构造——新的分配器可能不是get_allocator()的副本。

示例

#include <string>
#include <iostream>

int main()
{
std::string a = "0123456789abcdefghij";

// count is npos, returns [pos, size())
std::string sub1 = a.substr(10);
std::cout << sub1 << '\n';

// both pos and pos+count are within bounds, returns [pos, pos+count)
std::string sub2 = a.substr(5, 3);
std::cout << sub2 << '\n';

// pos is within bounds, pos+count is not, returns [pos, size())
std::string sub4 = a.substr(a.size()-3, 50);
// this is effectively equivalent to
// std::string sub4 = a.substr(17, 3);
// since a.size() == 20, pos == a.size()-3 == 17, and a.size()-pos == 3

std::cout << sub4 << '\n';

try {
// pos is out of bounds, throws
std::string sub5 = a.substr(a.size()+3, 50);
std::cout << sub5 << '\n';
} catch(const std::out_of_range& e) {
std::cout << "pos exceeds string size\n";
}
}
输出
abcdefghij
567
hij
pos exceeds string size
本文源自此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了修改。点击“编辑此页面”查看本文档所做的所有更改。
悬停查看原始许可证。