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

时间:2010-05-09 05:33:35

标签: c++

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

3 个答案:

答案 0 :(得分:11)

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

如果您尝试从C样式字符串(NUL终止的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); 数组)创建子字符串,则可以使用std::string(const char* s, size_t n)构造函数。例如:

std::string::substr

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

答案 1 :(得分:6)

std::string thesub = thestring.substr(start, length);

std::string thesub = thestring.substr(start, end-start+1);

假设您希望end字符包含在子字符串中。

答案 2 :(得分:0)

您可以使用std:string class的substr方法。

相关问题