将多行字符串转换为一个字符串。

huangapple go评论71阅读模式
英文:

Convert multiple lines of string into one string

问题

当我打印s时,它会输出:

what is coding
sky is green
ocean is gold

我该怎么做才能使其输出为:

what is coding sky is green ocean is gold

我已经尝试过 s.replace("\n\r", "") 和使用 System.lineSeparator(),但都没有成功。

我做错了什么?

英文:

Let's say I have a code that reads each line of text from a text file and store it into a variable String s.

while (file.hasNext()){
     String s = file.nextLine();
}

When I print s, it prints out

what is coding
sky is green
ocean is gold

What can I do to so that it prints out

what is coding sky is green ocean is gold

I've tried to do s.replace("\n\r", "") and using System.lineSeparator() but to no avail.

What am I doing wrong?

答案1

得分: 1

我希望你一切安好。

    Scanner scanner = null;
    String line = "";
    try {
        scanner = new Scanner(new File("D:\\ExampleFile.txt"));
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    }
    while (scanner.hasNextLine()) {
      // 这是你问题的关键。
      line += scanner.nextLine();
    }
    System.out.println(line);
英文:

I hope you are fine.

    Scanner scanner = null;
    String line = "";
    try {
        scanner = new Scanner(new File("D:\\ExampleFile.txt"));
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    }
    while (scanner.hasNextLine()) {
      // This is the key for your problem.
      line += scanner.nextLine();
    }
    System.out.println(line);

答案2

得分: 0

尝试

String fileWithoutNewLine = FileUtils.readFileToString(new File(<PATH_TO_FILE>)).replaceAll("\n", "");
英文:

Try

String fileWithoutNewLine = FileUtils.readFileToString(new File(&lt;PATH_TO_FILE&gt;)).replaceAll(&quot;\n&quot;, &quot;&quot;)

huangapple
  • 本文由 发表于 2020年10月1日 07:28:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64147106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定