当我阅读java文件时,如何忽略注释语句/*.*。

时间:2016-03-01 23:33:57

标签: java file bufferedreader

如何忽略以function add($arr){ extract($arr, EXTR_REFS); return $one+$two; } $one = 1; $two = 2; echo add(compact('one', 'two')); // 3 开头并以...结尾的注释语句 例如"/*""*/"/*the problem is..*/,我想逐行读取java文件时删除这些语句

/* problem is very difficult */

1 个答案:

答案 0 :(得分:-1)

只需包括:

int index =  str.indexOf("/*");

while(index != -1) {
    str = str.substring(0, index) + str.substring(str.indexOf("*/")+2);
    index =  str.indexOf("/*");
}

修改 假设您必须考虑片段的开头或结尾中断注释的片段:
EDIT2: 现在..还假设您必须考虑文字字符串"/*""*/"

str = str.replace("\"/*\"", "literal_string_open_comment");
str = str.replace("\"*/\"", "literal_string_close_comment");

int start =  str.indexOf("/*"), end = str.indexOf("*/");

while(start > -1 || end > -1) {
    if(start != -1) {
        if(end != -1) {
            if(end < start) {
                str = str.substring(end+2);
            } else {
                str = str.substring(0, start) + str.substring(end+2);
            }
        } else {
            str = str.substring(0, start);
        }
    } else {
        str = str.substring(end+2);
    }

    start =  str.indexOf("/*"); 
    end = str.indexOf("*/");
}

str = str.replace("literal_string_open_comment", "\"/*\"");
str = str.replace("literal_string_close_comment", "\"*/\"");