copying a substring from a string given end index in string
std::string thesub = thestring.substr(start, length);
or
std::string thesub = thestring.substr(start, end-start+1);
assuming you want the end
th character to be included in the substring.
From a std::string
, std::string::substr
will create a new std::string
from an existing one given a start index and a length. It should be trivial to determine the necessary length given the end index. (If the end index is inclusive instead of exclusive, some extra care should be taken to ensure that it is a valid index into the string.)
If you're trying to create a substring from a C-style string (a NUL-terminated char
array), then you can use the std::string(const char* s, size_t n)
constructor. For example:
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);
Unlike std::string::substr
, the std::string(const char* s, size_t n)
constructor can read past the end of the input string, so in this case you also should verify first that the end index is valid.