Copying a substring from a string specified by a trailing index in a string

How can I copy a substring from a given string with a start and end index, or specify a start index and string length.

Thanks, ISight

+5
source share
3 answers

From std::string, std::string::substrwill create a new one std::stringfrom the existing one, given the initial index and the length. It should be trivial to determine the necessary length, given the final index (although this will depend on whether the final index is included or excluded).

If you are trying to create a substring from a C-style string (NUL-end char), you can use std::string(const char* s, size_t n). 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);
+6
source
std::string thesub = thestring.substr(start, length);

or

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

, end th .

+7

You can use the substr method od std: string class.

0
source

All Articles