简体   繁体   English

无法以“ \\ n”开始新行?

[英]Cannot start new line with “\n”?


I am working on a project and there is a small part of it really confusing me. 我正在做一个项目,其中有一小部分确实让我感到困惑。 Say I have a String array : 说我有一个String数组:

String[]text = {"string","array"}; 

for example. 例如。
And I want to make it to a single String with a new line "\\n" between every single word. 我想将其设置为单个字符串,并在每个单词之间添加新行“ \\ n”。 So here is my code 所以这是我的代码

public String setText(String [] text) throws UnsupportedEncodingException{
    StringBuffer result = new StringBuffer();
    String newline = System.getProperty("line.separator");
    if (text.length > 0) {
        result.append(text[0]);
        for (int i=1; i<text.length; i++) {
            result.append(newline);
            result.append(text[i]);
        }
    }
    return result.toString();
}

My code doesnt work. 我的代码不起作用。 The return value is a single string but when I use it, it is still in one line. 返回值是一个字符串,但是当我使用它时,它仍然在一行中。

Anyone can help me with this? 有人可以帮我吗?

Thank you 谢谢

Allan 艾伦

Did you see what System.getProperty("line.separator"); 您是否看到了System.getProperty("line.separator"); returns? 退货? In different OS it will be different symbols \\n - Linux and \\r\\n in Windows Try to use System.getProperty("line.separator", "\\r\\n"); 在不同的操作系统中,它将是不同的符号\\n -Windows中的Linux和\\r\\n尝试使用System.getProperty("line.separator", "\\r\\n"); or System.getProperty("line.separator", "\\n"); System.getProperty("line.separator", "\\n");

Depends on how you use the result. 取决于您如何使用结果。 Have you tried writing it to System.out / a file or anything similar? 您是否尝试过将其写入System.out /文件或类似文件?

我建议使用Google的Guava库中的 Joiner

Joiner.on(System.getProperty("line.separator")).join(text)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM