tags:

views:

63

answers:

3

Hi,

How can i copy a substring from a given string with start and end index or giving the start index and length of the string are given.

Thanks, iSight

+2  A: 

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 (although it will depend on whether the end index is inclusive or exclusive).

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);
jamesdlin
Note, that doesn't check for `end` being past the end of the C string.
Potatoswatter
+1  A: 
std::string thesub = thestring.substr(start, length);

or

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

assuming you want the endth character to be included in the substring.

Alex Martelli
A: 

You can use substr method od std:string class.

Devara Gudda