Search code examples
javastring-concatenation

Concatenate auto generated strings in java with a space seperator in between


I have a string array variable which values changes continuously. Random arrays are generated from it. This is what i have:

String trans = Utility.GetColumnValue(testdata[k], "suggest_text_2");

The trans value changes continuously. How can i concatenate it with the previous values? How can i print every value of trans as it changes continuously? Do i need to use any buffer?


Solution

  • If you need the intermediate results, you will probably need something like this:

    String yourOldString;
    String freshString;
    
    // other code which updates freshString
    yourOldString = yourOldString + " " + freshString;
    

    However if you do need to catch all updates but only print out the final result, use a StringBuilder:

    private static final String WHITESPACE = " ";
    
    String yourOldString;
    String freshString;
    StringBuilder builder = new StringBuilder();
    builder.append(yourOldString);
    
    // other code which updates freshString
    builder.append(WHITESPACE);
    builder.append(freshString);
    
    // once everything is done:
    String resultString = builder.toString();