2

I want to display an array of Strings with space between words like this:

One Two Three

I have tried this:

Display.setText( " " + swappedString);

But if i do it that way, the first word will have space before it. I don't want that space.

5 Answers 5

10

Since Java 8 we can use

String joined = String.join(" ", yourStringArray);
Sign up to request clarification or add additional context in comments.

Comments

2

You can also try this simple solution :

String []inputStr = {"One","Two","Three"};
StringBuilder resultStr = new StringBuilder();
for (int i = 0; i < inputStr.length; i++) {
   if (i > 0) {
      resultStr.append(" ");
    }
   resultStr.append(inputStr[i]);
}

System.out.println(resultStr.toString());

Comments

0

You can use this also :

String [] myArray = {"One","Two","Three"};
StringBuilder builder = new StringBuilder();
for (String value : myArray) {
builder.append(value).append(" ");
}
System.out.println(builder);

1 Comment

Don't do append(value+" "). Write it as append(value).append(" "). value+" " would need to create new StringBuilder to concatenate these values which we don't need since we already have one created.
0

Just use trim() function of String to get rid of extra space (before or after) in the space.
See the sample code to get how it works:

        String result = "";
        String[] strings = new String[]{"One", "Two", "Three"};
        for (String string : strings) {
            result = result + string + " ";
        }
        result = result.trim();
        System.out.println(">" + result + ">");

One outside suggesation is, use StringBuilder. It does not create object every time.Sample Code:

        StringBuilder stringBuilder = new StringBuilder();
        String[] strings = new String[]{"One", "Two", "Three"};
        for (String string : strings) {
            stringBuilder.append(string);
            stringBuilder.append(" ");
        }
        String result = stringBuilder.toString().trim();
        System.out.println(">" + result + ">");

Comments

0

Im pointing out the obvious:

Display.setText(swappedString + " ");

This does, however, add a space at the end of the String.

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.