5

I have a string that supposed to return a concatenation of multiple strings such as "bob" "bill" "steve". The end result should look like "bob bill steve". How can I add a space without adding one before or after the final words using Java?

1
  • Are these strings part of an array? Where are you getting "bob" "bill" "steve" from? Commented Sep 29, 2012 at 20:26

8 Answers 8

12

Using Guava Libraries:

String[] names = {"bill", "bob", "steve" };
String fullString = Joiner.on(" ").join(names);

In Java 8:

String fullString = String.join(" ", names)
Sign up to request clarification or add additional context in comments.

2 Comments

@svz why reinvent the wheel? (Unless you are in Academia)
@svz Now no need for 3rd party lib with Java 8 to get simple one-liner
3

This is the way I'm doing it

public static boolean isEmpty(String string) {
    return string == null || string.trim().length() == 0;
}

public static String concatenate(final String separator, final String... parameters) {

    StringBuilder result = new StringBuilder("");

    for (String param : parameters) {
        if (!isEmpty(param)) {
            if (result.length() > 0) {
                result.append(separator);
            }
            result.append(param);
        }
    }

    return result.toString();
}

2 Comments

Doesn't a String class have its own isEmpty() method?
Not with the trim behavior. I prefer to trim the parameters to avoid multiple spaces. You can use String.isEmpty if you don't need this feature.
1

I would suggest using a StringBuilder, in case you're iterating through an array of String. Something like this:

StringBuilder buffer = new StringBuilder();

//Assuming you have a string array;

int length = stringArray.length;

for(int index = 0; index < length; index++){
    if(index > 0)
        buffer.append(" ");
    buffer.append(stringArray[index]);
}

return buffer.toString();

4 Comments

@MadProgrammer: Ah well...finally :D :D
However I'd use something like if (buffer.length() == 0) instead of if(index > 0), but that's just me...
Also, you'll get better performance out of StringBuilder if you provide an initial size, similar to something like ArrayList, doesn't have to be exact, just provides the buffer the ability to grow better
@MadProgrammer: I agree that would indeed be a performance benefit.
1

It sounds like you're iterating over the strings to concatenate, something like:

StringBuilder sb = new StringBuilder();
for (String str : strings)
    sb.append(str).append(" ");  
result = sb.toString();

And you end up with a space at the end. If so, you can use the String.trim method to get rid of that extra space:

result = result.trim();

trim removes all leading and trailing whitespace.

Comments

0

You can use a StringBuilder to build your string like this:

StringBuilder sb = new StringBuilder();
sb.append("bill").append(" ");
//and so on..

If your values are in a list or an array you can use a for loop to build your string. Something like:

foreach(String s: strings){
    sb.append(s).append(" ");
}
sb.toString.trim();

Comments

0

Because using "+" in loops isn't the best idea, you can try also with:

    String foo [] = {"asd", "bbb", "ccc"};
    StringBuilder sb = new StringBuilder();
    for (String string : foo) {
        sb.append(string).append(" ");
    }
    String result = sb.toString().trim();

Comments

0

Ah yes ... one of my favourites ... you are looking for a Separator. Here's one. It comes with some sample static utility methods to demonstrate its use. There are many more usages.

public class Separator {
  private final String sepString;
  private final String firstString;
  boolean first = true;

  // Use for url params ("?","&").
  public Separator(final String first, final String sep) {
    this.sepString = sep;
    this.firstString = first;
  }

  // Use for commas etc.
  public Separator(final String sep) {
    this("", sep);
  }

  public String sep() {
    // Return empty string first and then the separator on every subsequent invocation.
    if (first) {
      first = false;
      return firstString;
    }
    return sepString;
  }

  public void reset() {
    first = true;
  }

  @Override
  public String toString() {
    return first ? "(" + sepString + ")" : sepString;
  }

  // Utilities.
  public StringBuilder addAll(final StringBuilder buf, final Iterable<?> values) {
    if (null == values) {
      return buf;
    }
    for (final Object v : values) {
      buf.append(sep()).append(v);
    }
    return buf;
  }

  public StringBuilder addAll(final StringBuilder buf, final Iterator<?> values) {
    if (null == values) {
      return buf;
    }
    while ( values.hasNext() ) {
      buf.append(sep()).append(values.next());
    }
    return buf;
  }

  public StringBuilder addAll(final StringBuilder buf, final Object... values) {
    if (null == values) {
      return buf;
    }
    for (final Object v : values) {
      buf.append(sep()).append(v);
    }
    return buf;
  }

  public StringBuilder addAll(final StringBuilder buf, final int... values) {
    if (null == values) {
      return buf;
    }
    for (final int v : values) {
      buf.append(sep()).append(v);
    }
    return buf;
  }

  public static String separate ( String separator, int [] ints ) {
    return new Separator(separator).addAll(new StringBuilder(), ints).toString();
  }

  public static String separate ( String separator, long [] longs ) {
    return new Separator(separator).addAll(new StringBuilder(), longs).toString();
  }

  public static String separate ( String separator, Object [] objs ) {
    return new Separator(separator).addAll(new StringBuilder(), objs).toString();
  }

  public static String separate ( String separator, Set them ) {
    return new Separator(separator).addAll(new StringBuilder(), them).toString();
  }

  public static String separate ( String separator, Iterator<?> i ) {
    return new Separator(separator).addAll(new StringBuilder(), i).toString();
  }

}

Comments

0

use java.util.StringJoiner

import java.util.StringJoiner;  
StringJoiner sj = new StringJoiner(" ");
sj.add("aaa");
sj.add("bbb");
sj.add("ccc");
String result = sj.toString();
System.out.println(result);

output: aaa bbb ccc

no need to write any logic.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.