Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing lines from a string containing certain character

Tags:

java

string

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?

like image 325
Serpace Avatar asked Oct 15 '25 15:10

Serpace


1 Answers

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();
like image 105
ankh-morpork Avatar answered Oct 18 '25 04:10

ankh-morpork