关于String的replaceAll方法的困惑

时间:2015-02-26 02:38:01

标签: 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没有被插入到我的字符串中。基本上我的输出行打印出与输入行相同的长度,并且单词不会在单独的行上打印出来。任何人都知道为什么或如何解决它?

1 个答案:

答案 0 :(得分:3)

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

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

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

相关问题