2010-05-09 35 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個字符。

相關問題