删除Java源代码中的注释

本文详细介绍了如何使用Java编写一个方法,去除给定代码字符串中的单行和多行注释,通过遍历字符串并记录注释状态来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//类似于有限状态机
import java.io.FileReader;
import java.io.IOException;


public class RemoveComment {
//遍历字符串,记录闭合状态
	public static String removeComment(String src){
		StringBuffer sb = new StringBuffer();
		int currentState=-1;  //0=",1=//,2=/*
		for(int i=0;i<src.length();i++){
			char c = src.charAt(i);
			if(c == '\"'){
				if(currentState==-1){
					currentState = 0;
					sb.append(c);
				}else if(currentState==0){
					currentState = -1;
					sb.append(c);
				}
			}else if(c=='/'){
				i++;
				if(i==src.length()){
					if(currentState!=1&¤tState!=2){
						sb.append("/");
					}
					break;
				}
				char next = src.charAt(i);
				
				if(next=='/'){
					if(currentState ==-1){
						currentState = 1;
					}else if(currentState == 0){
						sb.append("//");
					}
				}else if(next=='*'){
					if(currentState ==-1){
						currentState = 2;
					}else if(currentState == 0){
						sb.append("/*");
					}
				}else if(next=='\\'){
					if(currentState!=1&¤tState!=2){
						sb.append("/");
					}
					i--;
				}else if(next=='\\'){
					if(currentState!=1&¤tState!=2){
						sb.append("/");
					}
					i--;
				}
				else{
					if(currentState!=1&¤tState!=2){
						sb.append("/").append(next);
					}
				}
			}else if(c=='*'){
				i++;
				if(i==src.length()){
					if(currentState!=1&¤tState!=2){
						sb.append("*");
					}
					break;
				}
				char next = src.charAt(i);
				
				if(next=='/'){
					if(currentState == 2){
						currentState = -1;
					}else if(currentState!=1){
						sb.append("*/");
					}
				}else if(next=='\\'){
					if(currentState!=1&¤tState!=2){
						sb.append("*");
					}
					i--;
				}else{
					if(currentState!=1&¤tState!=2){
						sb.append("*").append(next);
					}
				}
			}else if(c=='\n'){
		    	if(currentState == 1){
					currentState = -1;
				}
		    	sb.append("\n");
			}else if(c=='\\'){
				i++;
			    if(i==src.length()){
			    	if(currentState!=1&¤tState!=2){
			    		sb.append("\\");
			    	}
			    }
				char next = src.charAt(i);
				if(currentState!=1&¤tState!=2){
					sb.append("\\").append(next);
				}else{
					i--;
				}
			}else{
				if(currentState!=1&¤tState!=2){
					sb.append(c);
				}
			}
		}
		return sb.toString();
	}
	
	public static void main(String[] args) throws IOException {
		FileReader fr = new FileReader("D:\\workspace\\MyTest\\src\\test.txt");
		char[] cbuf = new char[4000];
		int length = fr.read(cbuf);
		String src = new String(cbuf,0,length);
		src = removeComment(src);
		System.out.println(src);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值