aspose file tools
The moose likes Java in General and the fly likes Concat strings Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Concat strings" Watch "Concat strings" New topic
Author

Concat strings

Angus Ferguson
Ranch Hand

Joined: Jun 22, 2012
Posts: 240
Hi
I need make something like

String c="";

and a List of String and for every position this values:

List cd=new ArrayList();
cd[0]=p1;
cd[1]=p2;
cd[2]=p3;
cd[3]=p4;
cd[4]=p5;



Then I want to create a long string with all the values concatenated using a loop

for (int i = 0; i < 5; i++) {

c.concat(cd[i]);

}
Then the result I am looking for is that c is equal to p1p2p3p4p5

Any idea, please?

Many Thanks
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 9944
    
    6

Strings are immutable. So, the concat() method doesn't change the current String, but creates a new one and returns that. you need to catch it and save it. probably something like:

c = c.concat(cd[i]);

Although, really, you would want to use a StringBuilder or StringBuffer to do this.


Never ascribe to malice that which can be adequately explained by stupidity.
R. Jain
Ranch Hand

Joined: Aug 11, 2012
Posts: 276

Have you tried to run the code, what you are trying to show here..
Just try and frame the raw code what you can think of.. And see what errors you get.. Probably that would be a better way to learn..

*FYI: - Always use generic types while using List, ArrayList and other Collection types..
See Generics


OCPJP
R. Jain
Ranch Hand

Joined: Aug 11, 2012
Posts: 276

R. Jain wrote:Have you tried to run the code, what you are trying to show here..
Just try and frame the raw code what you can think of.. And see what errors you get.. Probably that would be a better way to learn..

*FYI: - Always use generic types while using List, ArrayList and other Collection types..
See Generics



*EDIT: - Quoted by mistake
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 4739
    
    7

Angus Ferguson wrote:Then I want to create a long string with all the values concatenated using a loop

You can actually get something similar (and in my opinion, more readable) by using List.toString(); and then you wouldn't have to write any other code at all.

Give it a try and see if it's good enough for your purposes.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Concat strings
 
Similar Threads
Good Code? Bad Code?
explanation of getter/setter methods -- what's the difference exactly?
im trying to sort my program with insertionSort and selectionSort
Another executeUpdate() ?
Performance of Java Object Referece