remove comment

来源:互联网 发布:java选择题及答案 编辑:程序博客网 时间:2024/05/24 06:47


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 programfor (int i = 0; i < n; i++) {// If single line comment flag is on, then check for end of itif (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 itelse if (s_cmt || m_cmt) {continue;}// Check for beginning of comments and set the approproate flagselse 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 reselseres.append(prgm.charAt(i));}return res.toString();}}


0 0