计算没有评论的字符

Counting chars without comments

我正在尝试创建一个函数来计算字符串输入中的所有字符,但不计算任何注释(// 或 /*)

到目前为止,它可以完美地处理 // 之后的行。我将我的字符串拆分为每一行,如果它不包含 //

我只计算行字符

这是目前的代码:

function findComments() {

    var string = document.getElementById("input").value;
    var splittedString = string.split("\n");

    var count = 0;

    for (var i = 0; i < splittedString.length; i++) {
        while (countStars) {
            if(splittedString[i].indexOf("*/") > -1) {
                countStars = false;
            }
            continue;
        }

        if(splittedString[i].indexOf("/*") > -1) {
            var countStars = true;
        }

        if(splittedString[i].indexOf("//") === -1) {

            var chars = splittedString[i].split("");
            for (var j = 0; j < chars.length; j++) {
                count++;
            }
        }

    }
    console.log(count);
}

正如我提到的,它应该继续循环直到它找到注释的结尾 ( */ )。到目前为止这不起作用

非常感谢任何帮助! :)

 var inComment = false, count = 0;
 for(const line of splittedStrings){
  var end = -1;
  if(inComment){
   end = line.indexOf("*/");
   if(end === -1){
     count += line.length;
     continue;
   } else {
     count += end;
     inComment = false;
   }
  }
  const single = line.indexOf("//", end);
  const multi = line.indexOf("/*", end);
  if(single + multi === -2) continue;
  if(multi !== -1 && multi < single){
    //got a multiline comment
    inComment = true;
    count += line.length - (multi + 2);
 } else{
   //got a single line comment
   count += line.length - (single + 2);
 }
}

如果您在多行评论中,请保留标记

这可以进一步改进,但您可以用“/*”拆分原始文本,并从计数中减去块注释的长度。这意味着不必要地计算块评论,但它完成了工作。

像这样拆分文本,您知道数组中的每个第二项都是您的块注释。

var blockComments = string.split('/*');

function blockCommentsLength(array){
   length = 0;
   for (var i = 0; i < array.length; i = i +2){
      length += array[i].length
   }

   return length;
}

...

console.log(count - blockCommentsLength(blockComments));

您应该在 for 循环之外声明 countStars,因为您甚至在声明之前就检查了该变量
您应该从 while 循环中获取 continue 语句。继续会再次命中 while 语句。

for(var i = 0; i<10; ++i)
{
    var j = 10;
    var k = true;
    while(j > 0 && k)
    {
       j--;
       if(j == 8)
       {k == false;}
    }
    if(!k)
       continue;
}