1

I'm using eclipse, so I have this argument on the run configuration:

hello HELLO hello

Apparently, it's on String[] args. Is there a method that can concatenate all the array values ALONG with the empty spaces between them?

I have tried splicing the arrays into a char arrays, used the toString method(garbage value for some reason), and even StringBuilder. But it always gives values but not the spaces itself. @@

3 Answers 3

4

You can use the String.join method:

String[] arr = {"hello", "HELLO", "hello"};
System.out.println(String.join(" ", arr));

String#join is available in Java 8.

Using StringBuilder:

StringBuilder sb = new StringBuilder();
String sep = "";
for (String str : arr) {
  sb.append(sep);
  sb.append(str);
  sep = " ";
}
System.out.println(sb.toString());
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, forgot to add that comment.
1
try this 

 public static void main(String[] args)
{
    String concated = "";
    for(String arg:args){
        concated+=arg+" ";
    }

    System.out.println(concated);
}

Comments

1

Well if I understood your question correctly, you have such array:

string[] str = new string[3] { "Hello", "HELLO", "hello"};

If you want them to have spaces between each words you can do something like

string output = "";

    for(int i = 0; i< str.length; i++)
    {
          if(i + 1 != str.length)
          {
              output += str[i] + " ";
          }
          else
          {
              output += str[i];
          }  
    }

3 Comments

Well it should demonstrate the point in Java too, in my opinion.
Just some problems with this code, you using str even though it is an array. So seems like you forgot the index values when using output += str [ i ] + " ";. Moreover, it is Java, hence, Length should be length, with small l not capital `L' :-). Though rest of the logic is corrent
Thanks for your comment. I do not know what I was thinking when I wrote the answer for the first time. I believe it is correct now.

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.