Search code examples
javaparsingbufferedreaderbufferedwriterreplaceall

Confusion about String's replaceAll method


I'm attempting the will essentially take an input file and write out an output file that has each word and punctuation of the input on a separate line.

Example input:

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

Example output:

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

here is my code:

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");
                    }

                }
            }

I'm dealing with a couple bugs at the moment, but my main one is that \n is not being inserted into my strings. basically my output lines are printing out the same length of my input lines and words are not being printed out on separate lines. Anyone know why or how to fix it?


Solution

  • replaceAll doesn't modify the string you call it on, it returns a new string. Make sure you capture its return value.

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

    (In fact Strings are immutable, so this is true of all String methods. They never change the string.)