扫描仪next() - 如何替换换行符[java]

时间:2017-01-26 22:03:43

标签: java arrays newline replaceall

我撞墙了!

在StackOverflow上阅读了很多有趣的线程后,我尝试了很多不同的解决方案,但似乎没什么用。

假设我有一个.txt文件,我想用“XXX”替换换行符。我使用count方法来计算文档中的行。

Scanner reader = new Scanner("document.txt);

String [] textToArray = new String[count];

for(int i = 0; textToArray.length; i++){
String text = reader.nextLine();

text = text.replaceAll("\n", "XXX");
textToArray[i] = text;

}

然后我使用a为每个循环打印出文本。输出仍然与原始输出相同。

我也试过“\ n”,“\ r”,“\ r”甚至“\ r \ n”。

3 个答案:

答案 0 :(得分:1)

阅读文档,即nextLine()

的javadoc
  

使此扫描程序超过当前行并返回跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。该位置设置为下一行的开头。

因此,您正在阅读每行的文字,但您不会看到\r和/或\n字符。

由于您正在将每一行读入数组,因此您应该只为每个值附加XXX

for (int i = 0; textToArray.length; i++) {
    String text = reader.nextLine();
    textToArray[i] = text + "XXX";
}

<强>相依

我还建议您阅读List而不是数组。之后你总是可以转换为数组。

我希望你记得关闭Scanner,并且你展示了模拟代码,因为new Scanner("document.txt")将扫描文本document.txt,而不是文件的内容。

String[] textToArray;
try (Scanner reader = new Scanner(new File("document.txt"))) {
    List<String> textList = new ArrayList<>();
    for (String text; (text = reader.nextLine()) != null; ) {
        textList.add(text + "XXX");
    }
    textToArray = textList.toArray(new String[textList.size()]);
}

答案 1 :(得分:0)

<div class="container">
  <div class="item"></div>
  <div class="item active"></div>
  <div class="item"></div>
</div>

.container {
  display: flex;
  height: 400px;
  margin: 50px;
}

.item {
  min-width: 33.33%;
  background: blue;
}

.item.active {
  margin-top: -40px;
  margin-bottom: -40px;
  background: red;
  border-radius: 10px;
}

当你读取一行时,没有换行可以触发全部替换。你将在文本中找到你在那一点上读到的任何一行。

尝试构建字符串或将全文放在String中,然后替换新行。

答案 2 :(得分:0)

如果我理解您的问题,您想在给出的示例中将XXX替换为“\ n”?将整个文件读取到一个字符串会更容易:

String file = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);

然后您可以使用内置函数,例如:

String replace(char oldChar, char newChar);

这将返回一个包含您的文件的新字符串,所有空格都替换为XXX。或者你想在那里使用的任何角色。