java - 关于 String 的 replaceAll 方法的困惑

标签 java parsing bufferedreader bufferedwriter replaceall

我正在尝试将本质上是获取一个输入文件并写出一个输出文件,该输出文件将输入的每个单词和标点符号放在单独的一行上。

示例输入:

 System.out.println("hey there");

示例输出:

 System.out.println
 (
 "hey
 there"
 )
 ;

这是我的代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

public class TokenSplitter {


private BufferedReader input;
private BufferedWriter output;

public TokenSplitter(BufferedReader input, BufferedWriter output) { //take our input and output
    this.input = input;
    this.output = output;
}

public void split() throws IOException {
    while (input.readLine() != null) { //read each line
        if (!input.readLine().isEmpty()) {
            String currentLine = input.readLine();
            for (int i = 0; i < currentLine.length(); i++) {
                if (currentLine.length()>1) {
                    if ((currentLine.charAt(i) == '/' && (currentLine.charAt(i + 1) == '/' || (currentLine.charAt(i + 1) == '*')))
                            || currentLine.charAt(1) == '*') {//locate if there are comments
                        currentLine = currentLine.substring(0, i);
                    }
                }
            }


                    currentLine.replaceAll(" ", "\n"); //new if there is a space, we know we finished a token
                    currentLine.replaceAll(";", "\n;");
                    currentLine.replaceAll("\\(", "\n(\n"); //with '(' we need to split before and after
                    currentLine.replaceAll("\\)", "\n)\n");
                    if (!currentLine.isEmpty()) {

                        output.write(currentLine + "\n");
                    }

                }
            }

我目前正在处理几个错误,但我主要的错误是\n 没有被插入到我的字符串中。基本上我的输出行打印出与我的输入行相同的长度,并且单词没有打印在不同的行上。任何人都知道为什么或如何解决它?

最佳答案

replaceAll 不会修改您调用它的字符串,它会返回一个新字符串。确保捕获其返回值。

currentLine = currentLine.replaceAll(" ", "\n");
currentLine = currentLine.replaceAll(";", "\n;");
currentLine = currentLine.replaceAll("\\(", "\n(\n");
currentLine = currentLine.replaceAll("\\)", "\n)\n");

(事实上 String 是不可变的,所以所有 String 方法都是如此。它们永远不会改变字符串。)

关于java - 关于 String 的 replaceAll 方法的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28733538/

相关文章:

java - 序言中不能有内容

Java:用于删除 XML 文件部分内容的正则表达式

java - BufferedReader 并填充一个 int 数组

java - java从文本文件中的特定位置获取单词

java - Spring ApplicationContext - 资源泄漏 : 'context' is never closed

java - 如何解决 "no db_java-6.2 in java.library.path"问题?

java - 使用 BufferedReader 读取多个文件

java - BufferedReader - 计算包含字符串的行数

java - 如何将 jstring 转换为 wchar_t *

java - Alfresco - 添加文件后运行自定义工作流程