How to concatenate arrays with space?

Viewed 2191

I don't get it why my arrays don't concatenate,its just that when I concatenate my arrays with any other character, it doesn't show the content of the tempString. But when I remove the special characters, it produces the output.

E.G When there is no special character, the output is //ThisisaSingleLineComment But when I use other special characters, there is no output at all

The Codes I used are the ff.:

tempString=tempString+newTokens[ctr];

tempString+=newTokens[ctr];

I even used string builder with this code, still there is no output.

StringBuilder sb = new StringBuilder(100);
sb.append(newTokens[ctr]);
sb.append(whiteSpace);

My output should look like this // This is a Single Line Comment

Since each and every one of those are assigned in an array that I want to combine to form a single string / queue(stack) value.

3 Answers

Why not using String#join

String[] newTokens ={"This","is","a","Single","Line","Comment"};
System.out.println(String.join(" ",newTokens));

And, output is

This is a Single Line Comment

Your code block while using tempString var should be like below

String tempString = newTokens[0]; 

Above statement is to simply to initialize an tempString var against first token received.

For any new token the concatenation should look like this. Or simply token at index 1 till last index of the array.

for(int ctr = 1; ctr < newTokens.length; ctr++) {
    tempString = tempString + "\b" + newTokens[ctr];
}

You are missing adding a whitespace character in your code. \b is escape character for a blank space or a single whitespace.

You can also use below statement

tempString = tempString + " " + newTokens[ctr] 

I would suggest you put your whole method block for StringBuilder part.

I am not sure of the input or array value you are running your code with.

Typically you will have to run this inside a loop to generate whole string with the StringBuilder.

Sample code for StringBuilder would look like this

StringBuilder sb = new StringBuilder(100);

for(int ctr = 0; ctr < newTokens.length; ctr++) { 
    sb.append(newTokens[ctr]);
    sb.append(whiteSpace);
}

Your code which is below is incorrect for concatenation.

tempString=tempString+newTokens[ctr];

tempString+=newTokens[ctr];

Both the statements what it does is it concatenates to last updated value of tempString.

For example, you first initialized tempString with " " a blank space.

First iteration would make the string value as " //". Now the tempString is not simply a whitespace character. You will have to add a new whitespace character separately as I showed in the above examples

You can also use a StringJoiner:

    StringJoiner joiner = new StringJoiner(" ");
    for(String string : myList){
        joiner.add(string);
    }
    System.out.println( joiner.toString() );
Related