Removing lines from a string containing certain ch

2020-07-24 04:34发布

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?

标签: java string
3条回答
成全新的幸福
2楼-- · 2020-07-24 04:44

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.

查看更多
神经病院院长
3楼-- · 2020-07-24 04:50

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);
查看更多
The star\"
4楼-- · 2020-07-24 05:00

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();
查看更多
登录 后发表回答