今天需要帮人过滤掉代码中的注释。我又不熟悉脚本语言,走不了捷径,只用用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++都可以。Linux 下安装JDK 1.5,Eclipse 3.4,MyEclipse 7.1恢复Ubuntu 9.10引导相关资讯 Java C++
- C++程序员如何转Java (今 06:48)
- C++前置++与后置++的区别与重载 (04月14日)
- 打破C++ Const 的规则 (01月23日)
| - 自动生成C、C++、shell程序基本框 (04月27日)
- C++:后现代的系统编程语言 (02月06日)
- C++ 顺序容器基础知识总结 (01月23日)
|
本文评论 查看全部评论 (0)