歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

過濾掉Java或者C++ 注釋

今天需要幫人過濾掉代碼中的注釋。我又不熟悉腳本語言,走不了捷徑,只用用java寫。

就簡單的寫了一下程序,但是核心功能實現了。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TextFilter {
TextFilter(String fileName) {
   this.fileName = fileName;
}

/**
* 處理文件中的文本
*/
public void process() {
   Scanner scan = null;
   try {
    scan = new Scanner(new File(fileName));
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   }

   String strLine = "";
   while (scan.hasNextLine()) {
    strLine = scan.nextLine();
    StringBuilder strb = new StringBuilder();
  
    //效率方面考慮,先過濾掉空行
    if(strLine.trim().length() == 0)
    {
     continue;
    }
  
    // System.out.println("---"+strLine);
    int index = -1;
    int endIndex = -1;
    // 1.對第一種注釋過濾
    if (!hasPrefix && (index = strLine.indexOf("//")) >= 0) {
     if (index > 0) {
      strb.append(strLine.substring(0, index));
     }
    } else if (!hasPrefix && (index = strLine.indexOf("/*")) >= 0) {// 2.對第二種注釋過濾

     if (index > 0) {
      strb.append(strLine.substring(0, index));
     }
   
     if ((endIndex = strLine.indexOf("*/")) >= 0) {
      strb.append(strLine.substring(endIndex + 2));
     } else {//該注釋占多行
      hasPrefix=true;
     }
    } else if(hasPrefix && (endIndex = strLine.indexOf("*/")) >= 0){
     strb.append(strLine.substring(endIndex + 2));
     hasPrefix = false;
    }else if(!hasPrefix){
     strb.append(strLine);
    }
  
    //output
    if(strb.toString().trim().length()>0 )
    {
     System.out.println(strb);
    }
  
  
   }
}

private String fileName = null;
private boolean hasPrefix = false;

public static void main(String[] args) {
   new TextFilter("c:\\test.cpp").process();
}

}


測試了一下。對java和c++都可以。

Copyright © Linux教程網 All Rights Reserved