0

for example I have a file contain: "The background to this short story in germany" and another line contain: "The background to this short story in france"

and every line the word "germany" is changed to another word but in the same position

how can i print the word in this position in another file

2 Answers2

0

First you should read the file content and save it to a String. You can then analyze the String like so:

String sentence = "The background to this short story in germany";
String[] sentenceSplit = sentence.split(" ");
String value = sentenceSplit[sentenceSplit.length - 1];

Execute this code for each file with the different values. The changed word is value in this example.

AkashBhave
  • 749
  • 4
  • 12
0

If your 'The background to this short story in' part is not changing in every line then you may use pattern matching to get the new word .

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String args[]) {

        // String to be scanned to find the pattern.
        String pattern = "The background to this short story in (.*)";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.


        String file = "fileLocation";
        try (BufferedReader br = new BufferedReader(new FileReader(file ))) {
            String line;
            while ((line = br.readLine()) != null) {
                Matcher m = r.matcher(line);
                if (m.find()) {
                    System.out.println("Found value: " + m.group(0));

                    System.out.println("Found value: " + m.group(1)); // GIVES YOU THE NEW WORD

                } else {
                    System.out.println("NO MATCH");
                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

You will get the new word in m.group(1) .

bob
  • 4,595
  • 2
  • 25
  • 35