2010-05-09 38 views

回答

6

std::stringstd::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); 
+1

请注意,它不会检查'end'是否超过C字符串的末尾。 – Potatoswatter 2010-05-09 06:28:38

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

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

假设你想被列入子的end个字符。

相关问题