简体   繁体   中英

Removing lines from a string containing certain character

I am working a Java project to read a java class and extract all DOC comments into an HTML file. I am having trouble cleaning a string of the lines I don't need.

Lets say I have a string such as:

"/**
* Bla bla
*bla bla
*bla bla
*/

CODE
CODE
CODE

/**
* Bla bla
*bla bla
*bla bla
*/ "

I want to remove all the lines not starting with * .

Is there any way I can do that?

First, you should split your String into a String[] on line breaks using String.split(String) . Line breaks are usually '\\n' but to be safe, you can get the system line separator using System.getProperty("line.separator"); .

The code for splitting the String into a String[] on line breaks can now be

String[] lines = originalString.split(System.getProperty("line.separator"));

With the String split into lines, you can now check if each line starts with * using String.startsWith(String prefix) , then make it an empty string if it does.

for(int i=0;i<lines.length;i++){
    if(lines[i].startsWith("*")){
        lines[i]="";
    }
}

Now all you have left to do is to combine your String[] back into a single String

StringBuilder finalStringBuilder= new StringBuilder("");
for(String s:lines){
   if(!s.equals("")){
       finalStringBuilder.append(s).append(System.getProperty("line.separator"));
    }
}
String finalString = finalStringBuilder.toString();

Yes Java's String class has a startsWith() method that returns a boolean. You can iterate through each line in the file and check if each line starts with "*" and if it does delete it.

Try this:

File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String linesToRemoveStartsWith = "*";
String currentLine;

while((currentLine = reader.readLine()) != null) {
    // trim newline when comparing with lineToRemove
    String trimmedLine = currentLine.trim();
    if(!trimmedLine.startsWith(linesToRemoveStartsWith )) continue;
    writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close(); 
reader.close(); 
boolean successful = tempFile.renameTo(inputFile);

As far as I remember, you cannot delete lines from the text documents in-place in Java. So, you would have to copy the needed lines into a new file. Or, if you need to output the same file, just changed, you could read the data into memory, delete the file, create a new one with the same name and only output the needed lines. Although, frankly, for me it seems a bit silly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM