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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With