• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Concat strings

 
Isaac DurĂ¡
Ranch Hand
Posts: 859
2
Java Netbeans IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
R. Jain
Ranch Hand
Posts: 375
1
Java Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 375
1
Java Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10509
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic