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)构造函数可以读取输入字符串的末尾,因此在这种情况下,您还应首先验证结束索引是否有效.
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个字符包含在子字符串中.