简体   繁体   中英

Removing comments from code character by character [Java]

I need to remove comments from code, but in this case I'll have to do it without using

System.out.println(sourceCode.replaceAll("//.*|/\\*((.|\\n)(?!=*/))+\\*/", ""));

The program needs to check the code character by character to look for "/" and then proceed to check if the next character is "/" or "*" .

I'm looking for a good way to read through the code and check characters letter by letter

This is a classic problem given to new learners in Java. I would suggest to go for a simple approach as it is intended to help you practice your coding skills

  1. Read the java source code as a file in your program char by char.
  2. Search for comments beginning. In this case, there are 2, /* and // .
  3. Open a string buffer and start writing the read contents into it.
  4. If its /* , then don't write it in buffer. Keep on moving to next character till you find */ .
  5. Repeat till end of file is reached.
  6. If single line comments need to be removed, then same algorithm can be followed till you get a new line character.
  7. If you need help in reading from file char by char, refer to Java documentation.
  8. When end of file is reached, then write the string buffer back to the file.

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