copy one string into another

how to copy one string into another using LOOPS.(i am talking about default string class)??
the code given below does not work.
please teach me
void function(string str1)
{
string str2;
int i=0;
while(str1[i]!=NULL)
{
str2[i]=str1[i];
i++;
}
}
Of course it does not work. str2 has a size of 0.

Why not just do this?
1
2
3
4
5
6
string s1 ("Hello");
string s2 ("Hi");
cout << s1 << " " << s2 << endl;
s2 = s1;
s1 = "Bye";
cout << s1 << " " << s2 << endl;
Hello Hi
Bye Hello
Last edited on
Hi

string str2 = "" ; and than either use push_back or += operator, when you have to copy the source string using a loop
It is more efficient to either use operator= or to resize string 2 beforehand.
It is not, it is very simple

1
2
3
4
5
6
7
string s1 = "hallo I am Here";
string s2;
string s3;
for(int i = 0 ; i < s1.size() ; i++)
	s2.push_back(s1[i]), s3 += s1[i];

cout<<s1<<endl<<s2<<endl<<s3<<endl;
thanks to you man.it works
There is no such an entity as "default string class" in C++.
There are character arrays and template class std::string in C++.
I think that you meant character arrays. Then your function will look

1
2
3
4
5
6
7
8
9
10
char * CopyString( char *dest, const char *source )
{
   char *p = dest;

// the comparision is used that avoid compiler warning
// otherwise you can write simply while ( *p++ = *source++ );
   while ( ( *p++ = *source++ ) != '\0' ); 

   return ( dest );
}


If template class std:;string is used then it is better to assign one string to another withou writing any function

1
2
3
4
std::string source( "Hello" );
std::string dest;

dest = source;
LB wrote:
It is more efficient to either use operator= or to resize string 2 beforehand.
therockon7throw wrote:
It is not, it is very simple
1
2
3
4
5
6
7
string s1 = "hallo I am Here";
string s2;
string s3;
for(int i = 0 ; i < s1.size() ; i++)
	s2.push_back(s1[i]), s3 += s1[i];

cout<<s1<<endl<<s2<<endl<<s3<<endl;
It is more efficient to use operator= or to resize the string beforehand.
1
2
3
4
5
6
7
8
9
10
11
string s1 ("Hello, I am here."), s2, s3;
s2.reserve(s1.length());
s3.resize(s1.length(). '\0');
for(string::iterator it = s1.begin(); it != s1.end(); ++it)
{
    s2 += *it; //or s2.append(*it);
}
for(string::size_type i = 0; i < s1.length(); ++i)
{
    s3[i] = s1[i];
}



Note that it is both easier and more efficient to use operator= as I originally wrote: http://www.cplusplus.com/forum/general/63898/#msg345641

There is no reason ever to copy a std::string character for character unconditionally.
Last edited on
Topic archived. No new replies allowed.