public class RemoveComments {
public static void main(String[] args) {
String str = "e//b/*c*/d\nefee";
System.out.print(removeComments(str));
}
static String removeComments(String prgm) {
int n = prgm.length();
StringBuilder res = new StringBuilder();
// Flags to indicate that single line and multpile line comments. From
// have started or not.
boolean s_cmt = false;
boolean m_cmt = false;
// Traverse the given program
for (int i = 0; i < n; i++) {
// If single line comment flag is on, then check for end of it
if (s_cmt == true && prgm.charAt(i) == '\n')
s_cmt = false;
// If multiple line comment is on, then check for end of it.
else if (m_cmt == true && prgm.charAt(i) == '*' && prgm.charAt(i + 1) == '/') {
m_cmt = false;
i++;
}
// If this character is in a comment, ignore it
else if (s_cmt || m_cmt) {
continue;
}
// Check for beginning of comments and set the approproate flags
else if (prgm.charAt(i) == '/' && prgm.charAt(i + 1) == '/') {
s_cmt = true;
i++;
} else if (prgm.charAt(i) == '/' && prgm.charAt(i + 1) == '*') {
m_cmt = true;
i++;
}
// If current character is a non-comment character, append it to res
else
res.append(prgm.charAt(i));
}
return res.toString();
}
}