Search code examples
javareplaceall

How do i stop replaceAll from continuously replacing in a loop


What I want to do is look through a text file containing a list of Chinese words and individual characters and first replace any words and then any individual characters.

My problem is that the replaceAll I am using seems to be continuous replacing characters that have already been replaced.

For example if I entered: 重水 it would output cung5 seoi2

But if I entered 重水重 it would pick up the first two characters as a word and then the single character at the end to output cung5 seoi2 cung4

My database file looks like this:

重水,cung5 seoi2

重,cung4

水,seoi2

Code snippet

String output = null;

Scanner in = new Scanner(System.in);

System.out.println("Enter Chinese: ");
String input = in.nextLine();

BufferedReader br = null;

String sCurrentLine;

br = new BufferedReader(new FileReader("C:\\database.txt"));

while ((sCurrentLine = br.readLine()) != null) {

    String[] lineValues = sCurrentLine.split(",");
    if(input.contains(lineValues[0])) {
        input = input.replaceAll(lineValues[0], lineValues[1]+" ");
    }
}

output = input;

System.out.println(output);

Sample session

input > 重水水

output> 重水水

expected output> cung5 seoi2 seoi2


Solution

  • I have run this code, which is just a cleaned up version of yours:

    final Scanner in = new Scanner(System.in);
    System.out.println("Enter Chinese: ");
    String input = in.nextLine();
    BufferedReader br = new BufferedReader(new FileReader("database.txt"));
    for (String sCurrentLine; (sCurrentLine = br.readLine()) != null;) {
      final String[] lineValues = sCurrentLine.split(",");
      input = input.replace(lineValues[0], lineValues[1]+" ");
    }
    System.out.println(input);
    

    The two sessions I tried looked as follows:

    Enter Chinese: 
    重水重
    cung5 seoi2 cung4 
    
    Enter Chinese: 
    重水水
    cung5 seoi2 seoi2 
    

    Conclusion: this program works as required.


    As an aside, this is how you can rewrite it with Java 8 Streams:

    System.out.println("Enter Chinese: ");
    final String input = new Scanner(System.in).nextLine();
    final String result = new BufferedReader(new FileReader("database.txt")).lines()
      .map(line->line.split(","))
      .reduce(input, (acc, lineValues) -> acc.replace(lineValues[0], lineValues[1]+" "));
    System.out.println(result);