File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Concat strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Concat strings" Watch "Concat strings" New topic
Author

Concat strings

Isaac Ferguson
Ranch Hand

Joined: Jun 22, 2012
Posts: 331
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: 11230
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
R. Jain
Ranch Hand

Joined: Aug 11, 2012
Posts: 370
    
    1

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
R. Jain
Ranch Hand

Joined: Aug 11, 2012
Posts: 370
    
    1

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: 7652
    
  19

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?
Articles by Winston can be found here
 
 
subject: Concat strings