我使用以下代码来计算代码中的注释数:
StringTokenizer stringTokenizer = new StringTokenizer(str);
int x = 0;
while (stringTokenizer.hasMoreTokens()) {
if (exists == false && stringTokenizer.nextToken().contains("/*")) {
exists = true;
} else if (exists == true && stringTokenizer.nextToken().contains("*/")) {
x++;
exists = false;
}
}
System.out.println(x);如果注释中有空格,它就能工作:
例如:"/* fgdfgfgf */ /* fgdfgfgf */ /* fgdfgfgf */".
但是它不适用于没有空格的评论:
例如:"/*fgdfgfgf *//* fgdfgfgf*//* fgdfgfgf */".
发布于 2013-07-28 13:58:00
new StringTokenizer(str,"\n")标记/将str拆分成行,而不是使用默认的分隔符\t\n\r\f,它是空格、制表符、格式提要、回车和换行符的组合。
StringTokenizer stringTokenizer = new StringTokenizer(str,"\n");这指定换行符为唯一用于标记化的分隔符。
使用您当前的方法:
String line;
while(stringTokenizer.hasMoreTokens()){
line=stringTokenizer.nextToken();
if(!exists && line.contains("/*")){
exists = true;
}
if(exists && line.contains("*/")){
x++;
exists = false;
}
}对于多个注释,我尝试使用/\\* & \\*/作为split()中的模式,并在字符串中获得它们的长度,但不幸的是,由于不均匀的拆分,长度并不准确。
多个/单一评论可以是:(海事组织)
COMMENT=/* .* */
A = COMMENT;
B = CODE;
C = AB/BA/ABA/BAB/AAB/BAA/A;发布于 2013-07-28 14:12:56
在StringUtils中使用公朗类,您可以很容易地将其存档
String str = "Your String"
if (&& StringUtils.countMatches(str,"/*") != 0) {
//no need this if condition
} else if (StringUtils.countMatches(str,"*/") != 0) {
x = StringUtils.countMatches(str,"*/");
}
System.out.println(x);发布于 2013-07-28 18:41:43
这让我想起了Ruby/Perl/Awk等人的触发器。没有必要使用StringTokenizer。您只需要保持状态来计算带注释的行数。
*/,就会切换注释块开关。并切换到状态2/*并返回到状态1之前,将拒绝所有内容。就像这样
public static int countLines(Reader reader) throws IOException {
int commentLines = 0;
boolean inComments = false;
StringBuilder line = new StringBuilder();
for (int ch = -1, prev = -1; ((ch = reader.read())) != -1; prev = ch) {
System.out.println((char)ch);
if (inComments) {
if (prev == '*' && ch == '/') { //flip state
inComments = false;
}
if (ch != '\n' && ch != '\r') {
line.append((char)ch);
}
if (!inComments || ch == '\n' || ch == '\r') {
String actualLine = line.toString().trim();
//ignore lines which only have '*/' in them
commentLines += actualLine.length() > 0 && !"*/".equals(actualLine) ? 1 : 0;
line = new StringBuilder();
}
} else {
if (prev == '/' && ch == '*') { //flip state
inComments = true;
}
}
}
return commentLines;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println(countLines(new FileReader(new File("/tmp/b"))));
}上面的程序忽略空行注释或只有/*或*/的行。我们还需要忽略嵌套的注释,哪些字符串标记程序可能做不到。
示例文件/tmp/b
#include <stdio.h>
int main()
{
/* /******* wrong! The variable declaration must appear first */
printf( "Declare x next" );
int x;
return 0;
}返回1。
https://stackoverflow.com/questions/17908882
复制相似问题