【发布时间】:2012-08-28 08:27:46
【问题描述】:
我正在尝试使用 \n 创建一个字符串列表,但每当我添加多个字符串时,字符串都会缩进到前一个字符串的位置,因此示例输出为:
0 hello nain
1 test nain
2 huh nain
我不知道它为什么这样做。这是我创建字符串的代码:
String[] posts = currentTopic.getMessages("main");
//String[] postsOutput = new String[posts.length];
String postsOutput = "0 " + posts[0];
for(int i = 1; i < posts.length; i++){
postsOutput += "\n" + i + " " + posts[i];
//postsOutput[i] = i + posts[i];
}
sc.close();
return postsOutput;
我也尝试将 \n 移动到附加的末尾,但结果仍然相同。任何帮助将不胜感激。
谢谢
【问题讨论】:
-
使用
System.getProperty("line.separator")代替换行符。 -
顺便说一下,不要在字符串后面加上'+'运算符。使用 StringBuffer 或 StringBuilder,尤其是在循环中...您的代码将生成许多无用的对象(String 的实例)
-
不要使用StringBuffer,它不同步。
标签: java string newline indentation