Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String copying

Status
Not open for further replies.

robmif76

Programmer
Feb 1, 2003
10
GB
Seeing that strings are objects, how do I copy the contents of one string into another?

Cheers
Rob
 
just use the " = " " ahhh computers, how they made our lives much simpler ;) "
 
dJam lies!

i could tease you but instead ill tell you why...

String myString = new String("djam lies");
String danDoesnt = myString;

THERE IS STILL ONLY ONE STRING HERE!!!
there are two POINTERS to that one string.
djam didnt attend his C lectures.
try and use clone dude
 
i would suggest that you dannywild82 are over complicating things needlessly.

Having a 5 second glance at the Java documentation shows this
Code:
String(String original) 
           Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

so
Code:
String s1 = "fred"; // or String s1 = new String("Fred");
String s2 = new String(s1); // gives u a separate copy of s1

That is straight out of the manual, so why clone? seems like awaste of effort and complication too me.

Plus djam was correct, the s2 = s1 will give s2 the same contents as s1, it is only if robmif76 needs two separate object would he use the String
Code:
(String original)
command or the clone command if he wanted more complicated code. -------------------------------------------
There are no onions, only magic
-------------------------------------------
 
Thanks for your help ppl.....solved my problem now.

Cheers
Rob
 
jfryer you are correct

the reason i went into talking about objects, is that you can get away without understanding the underlying architecture for an example this simple, but later you will shoot yourself in the foot.

As in my signature - you need to understand what you are doing. i thought the clone method though more terse, illustrated the concepts better. i didnt say it was the only way. people often try and get a solution 'just for this problem', if they understood the concepts they wouldnt have needed a solution!

ie how many objects are created here:

String myString = new String(Fred);
String hisString = "Fred";
String otherString = myString;
String anotherStirng = "Duuuuuuuuuuude!";

answer = 2!!!!
argue all you want! <<< Why is everyone trying to get a quick fix???? If you bothered to LEARN the theory it would have worked the first time around!!!! Go to uni! >>>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top