How to remove comments from a string in Java

1 Answer

0 votes
public class RemoveComments {

    public static String stripComments(String input) {
        StringBuilder out = new StringBuilder();
        int i = 0;

        while (i < input.length()) {

            // Check for // single-line comment
            if (i + 1 < input.length() && input.charAt(i) == '/' && input.charAt(i + 1) == '/') {
                i += 2;
                while (i < input.length() && input.charAt(i) != '\n') {
                    i++;
                }
            }

            // Check for /* ... */ block comment
            else if (i + 1 < input.length() && input.charAt(i) == '/' && input.charAt(i + 1) == '*') {
                i += 2;
                while (i + 1 < input.length() &&
                       !(input.charAt(i) == '*' && input.charAt(i + 1) == '/')) {
                    i++;
                }
                if (i + 1 < input.length()) {
                    i += 2; // skip closing */
                }
            }

            // Normal character
            else {
                out.append(input.charAt(i));
                i++;
            }
        }

        return out.toString();
    }

    public static void main(String[] args) {
        String text =
            "int x = 10; // single-line comment\n" +
            "int y = 20; /* block comment */\n" +
            "int z = x + y; /* multi\n" +
            "line\n" +
            "comment */ return z;";

        String cleaned = stripComments(text);

        System.out.println(cleaned);
    }
}


/* 
run:

int x = 10; 
int y = 20; 
int z = x + y;  return z;

*/

 



answered 23 hours ago by avibootz
...