0

I have a sentence in my text file,

Moreover, human serum could significantly enhance the LPS-induced DV suppression in a CD14-dependent manner, indicating that the "binding" of LPS to CD14 was critical for the induction of virus inhibition.

How do I replace the 2nd occurrence of CD14 to AB45 and write back to the text file?

2 Answers2

0

For the algorithm itself,

file.indexOf("CD14", file.indexOf("CD14")+4)

can be used to locate the occurance (given that "file" is a string with all of the contents of your file). The second argument of "indexOf" asks for a start point. By calling indexOf twice, you find the first instance of the string than check for another instance skipping past the first instance (+4 since indexOf will return the start of the string, adding the length of the string skips over it). To replace the string,

int i = file.indexOf("CD14", file.indexOf("CD14")+4);
String s = file;
if(i != -1) s = file.substring(0,i) + "AD25" + file.substring(Math.min(i+4,file.length()), file.length());

If you're asking how to read/write a text file, try google. one example - Java: How to read a text file , another - http://www.javapractices.com/topic/TopicAction.do?Id=42

Community
  • 1
  • 1
Arhowk
  • 901
  • 4
  • 11
  • 22
0

There are several approaches to take in solving this one. A very simple but verbose approach would be:

public static void replaceSecondOccurence(String originalText, String replacementText) throws IOException {
    File file = new File("file.txt");
    InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
    StringBuilder fileContent = new StringBuilder();
    int content;
    while ((content = reader.read()) != -1) {
        fileContent.append((char) content);
    }
    reader.close();

    int index = fileContent.lastIndexOf(originalText);
    fileContent.replace(index, index + originalText.length(), replacementText);

    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file));
    writer.write(fileContent.toString());
    writer.close();
}
Anwuna
  • 1,077
  • 11
  • 18