从给定字符串中的结束索引的字符串复制子字符串

boo*_*oom 8 c++

如何从给定字符串复制带有开始和结束索引的子字符串,或者给出字符串的起始索引和长度.

jam*_*lin 11

从a std::string,std::string::substr将在std::string给定起始索引和长度的情况下从现有的创建新的.鉴于最终指数,确定必要的长度应该是微不足道的.(如果结束索引是包含而不是独占,则应该特别注意确保它是字符串的有效索引.)

如果您尝试从C样式字符串(NUL终止的char数组)创建子字符串,则可以使用std::string(const char* s, size_t n)构造函数.例如:

const char* s = "hello world!";
size_t start = 3;
size_t end = 6; // Assume this is an exclusive bound.

std::string substring(s + start, end - start);
Run Code Online (Sandbox Code Playgroud)

与此不同std::string::substr,std::string(const char* s, size_t n)构造函数可以读取输入字符串的末尾,因此在这种情况下,您还应首先验证结束索引是否有效.

  • 注意,这不会检查`end`是否超过C字符串的结尾. (2认同)

Ale*_*lli 6

std::string thesub = thestring.substr(start, length);
Run Code Online (Sandbox Code Playgroud)

要么

std::string thesub = thestring.substr(start, end-start+1);
Run Code Online (Sandbox Code Playgroud)

假设您希望第endth个字符包含在子字符串中.