Ok lets say I have a string array like so:
String[] example = {"Poopy", "55","coolio");
How could I change this, all into one String like so:
String whatIWant = "Poopy55coolio";
I appreciate it.
Printable View
Ok lets say I have a string array like so:
String[] example = {"Poopy", "55","coolio");
How could I change this, all into one String like so:
String whatIWant = "Poopy55coolio";
I appreciate it.
There may be a more efficient way, but I would create a String object set to "", then loop through concatenating each item in the array to my string object.
Code:String s = "";
Declare a String variable above a for loop, then loop through the array concatenating each item in the array into the String variable mentioned above. By concatenate I mean that you add each String held in the array to the summary String with the += operator. Note that if you have to do this a lot in your program, then you're better off using a SwingBuilder object instead a summary String.
Hmm wait, so if I do something like:
for (int counter = 0; counter < example.length; counter++) {
whatIWant += example[counter];
}
That will combine all the strings?
I completely forgot about the += operator.
A bit better: use a StringBuilder instead of concatenating Strings in a loop. Strings are immuatble so saying a+= b for two String values a and b, creates yet another String and forgets about the previous value of a. Read the API documentation of that class for the details.
kind regards,
Jos
Yep, we are in agreement as mentioned in post 3 above.
I try not to push this too hard to newbies as in most of their small apps it smells too much of premature optimization. However if they're doing this sort of call repetitively in a critical portion of their code, then it is absolutely correct.