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

青春壹個敷衍的年華 提交于 2019-12-12 15:19:10

问题


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?


回答1:


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();



回答2:


String a = "foo";
String space = " ";
String b = "bar";
String c = a+space+b;



回答3:


It's often best to use StringBuilder to concatenate strings:

String [] array { "fee", "fie", "foe", "fum" };

boolean firstTime = true;
StringBuilder sb = new StringBuilder(50);
for (String word : array) {
    if (firstTime) {
        firstTime = false;
    } else {
        sb.append(' ');
    }
    sb.append(word);
}

String finalResult = sb.toString();



回答4:


System.out.println("string1 "+"string2");



回答5:


Simply,

String trans = Utility.GetColumnValue(testdata[k], "suggest_text_2");
StringBuffer concat = new StringBuffer();
concat.append(test).append(" ");

Or,

StringBuffer concat = new StringBuffer();
concat.append(Utility.GetColumnValue(testdata[k], "suggest_text_2")).append(" ");

To concatenate/combine set of data.

for(String s: trans){
  concat.append(s).append(" ");
}

String concatenation(like trans + " ") is slower than the StringBuffer append(). I strongly suggest you to use StringBuilder. Because when combinig String on the fly StringBuffer is created and then using toString() converts to String.

Here is nice blog post to read to learn about performance of these two.



来源:https://stackoverflow.com/questions/16285257/concatenate-auto-generated-strings-in-java-with-a-space-seperator-in-between

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!