-2

I have the following code:

ArrayList<String> idattributes=new ArrayList();
idattributes.add("7");
idattributes.add("10");
idattributes.add("12");

I'm trying to convert it to a string like this:

String listString = "";
for (String s : idattributes) {
      listString += s + "\t";
} 
System.out.println(listString);

I get: "7   10  12  "

How could I remove those multiple spaces? I just want a string "7 10 12" Any other good way to convert idattributes to a String? Thanks

user2399013
  • 75
  • 1
  • 1
  • 6
  • Those aren't "multiple spaces;" they're tabs, which is exactly what `"\t"` tells the code to do. Why not use `List#toString()`? – Matt Ball May 31 '13 at 18:06
  • 4
    "\t" is a tab. if you want just a simple space, say so: listString += s + " "; – Dmitry B. May 31 '13 at 18:06
  • If you want a single space between items, then use `" "` instead of `"\t"`. If you mean the spaces at the end, `trim()`. – thegrinner May 31 '13 at 18:07

6 Answers6

1

Sometimes it pays not to try to be too smart and use an inefficient trim() :)

String listString = "";
for (String s : idattributes) {
    listString += s + " ";
} 
listString = listString.trim();

Unless you meant to have the tab in there, in which case

listString += s + "\t"

is fine, but the trim() is still required.

Mike Hogan
  • 9,933
  • 9
  • 41
  • 71
0

to get "7 10 12" code has to be like

String listString = "";
for (String s : idattributes) {
  listString += s + " ";
} 
System.out.println(listString.trim());
twid
  • 6,368
  • 4
  • 32
  • 50
0

You have a couple of options:

String listString = "";
for (String s : idattributes) {
      listString += s + " ";
} 
listString = listString.trim();

System.out.println(listString);

Or,

System.out.println(idattributes.toString());
bn.
  • 7,739
  • 7
  • 39
  • 54
0

First of all, replace the "\t" by " ", then choose between :

for (int i = 0 ; i < idattributes.size() ; i++)
{
    listString += itattributes.get(i);
    if (i != idattributes.size() - 1)
        listString += " ";
}

and :

your code, followed by listString.trim()

Bastien Pasdeloup
  • 1,089
  • 12
  • 19
0

Another good way is to use Guava's Joiner class.

 String listString = Joiner.on(" ").join( idattributes );
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0

It's a good idea to use StringBuilder instead of String. You can find more info here

StringBuilder sb = new StringBuilder();
for (String s : idattributes) {
      sb.append(s).append(" ");
} 
String listString = sb.toString().trim()l
System.out.println(listString);

Also you can use the Joiner of the Guava lib.

String listString = Joiner.on(" ").join( idattributes ).trim();
Community
  • 1
  • 1
Petros Tsialiamanis
  • 2,718
  • 2
  • 23
  • 35