how can i extract all the elements in a string [] or arraylist and combine all the words with proper formating(with a single space) between them and store in a array..

String[] a = {"Java", "is", "cool"};

Output: Java is cool.

share|improve this question

58% accept rate
feedback

2 Answers

up vote 1 down vote accepted

Use a StringBuilder.

String[] strings = {"Java", "is", "cool"};
StringBuilder builder = new StringBuilder();

for (String string : strings) {
    if (builder.length() > 0) {
        builder.append(" ");
    }
    builder.append(string);
}

String string = builder.toString();
System.out.println(string); // Java is cool

Or use Apache Commons Lang StringUtils#join().

String[] strings = {"Java", "is", "cool"};
String string = StringUtils.join(strings, ' ');
System.out.println(string); // Java is cool
share|improve this answer
is there a easy way out because i m not that advance in java.. – user647207 May 8 '11 at 3:35
If there was an easy API-provided way, I'd have answered it. If you need to do it repeatedly, just hide it away in an utility method or just drop commons-lang.jar in classpath. – BalusC May 8 '11 at 3:36
feedback

My recommendation would be to use org.apache.commons.lang.StringUtils:

org.apache.commons.lang.StringUtils.join(a, " ");
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.