Copying fragment of a string to another string.

Hello, I am having problems copying part of a string into another string. For example, I tried the following:

int main()
string one;
getline(cin, one); //I want 'I like chips' to be in the string two.
string two;
int subtwo = 0;

for (int i = 8; i < 20; i++)
two[subtwo] = one[i];
cout << one << endl;
cout << two << endl;

I want "I like chips" to be in string two but it is not working. What is the right way to do this? Thank you.
First of all it is not clear why you decided that string one has 20 elements. The task can be performed simpler:

two = one;

provided that string one is equal to the string literal you want to copy.
Last edited on
Ok, I did not make my self clear. Let say I have the string "I like basketball", I would like to make another string with just "basketball" form the original string.
If you know the position from which the string literal is started and the length of the string literal then you can write simply

std::string one = "I like basketball";
std::string two( one, 7, 10 );

std::cout << two << std::endl;

// or

std::string third;
third.assign( one, 7, 10 );

std::cout << third << std::endl;
Last edited on
Or even you can do the following way

std::string one = "I like basketball";

std::string two( "He likes" );
two += ' ';
two.append( one, 7, 10 );

std::cout << two << std::endl;
Awesome, thanks.
Topic archived. No new replies allowed.