Apr 30, 2013 at 11:06pm UTC
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];
subtwo++;
}
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.
Apr 30, 2013 at 11:11pm UTC
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 Apr 30, 2013 at 11:15pm UTC
Apr 30, 2013 at 11:23pm UTC
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.
Apr 30, 2013 at 11:40pm UTC
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 Apr 30, 2013 at 11:40pm UTC
Apr 30, 2013 at 11:48pm UTC
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;