清除C/C++/JAVA中的注释

6 篇文章 0 订阅

 

import java.io.FileInputStream;
import java.io.PrintStream;
import java.util.Scanner;

/* ********\\\\\\\\\\/********
 this is test program
 this is test program
 this is test program
 */
public class Solution {
	private static final char MARK = '"';

	private static final char SLASH = '/';

	private static final char BACKSLASH = '\\';

	private static final char STAR = '*';

	private static final char NEWLINE = '\n';

	private static final int TYPE_MARK = 1;

	private static final int TYPE_SLASH = 2;

	private static final int TYPE_BACKSLASH = 3;

	private static final int TYPE_STAR = 4;

	private static final int TYPE_DSLASH = 5;

	public static String removeComment(String s) {
		int preType = 0;
		int mark = -1, cur = -1, token = -1;
		char[] input = s.toCharArray();
		for (cur = 0; cur < input.length; cur++) {
			if (input[cur] == MARK) {
				if (preType == TYPE_BACKSLASH)
					continue;
				if (mark > 0) {
					mark = -1;
				} else {
					mark = cur;
				}
				preType = TYPE_MARK;
			} else if (input[cur] == SLASH) {
				if (mark > 0)
					continue;
				if (preType == TYPE_STAR) {
					input = del(input, token, cur);
					cur = token - 1;
					preType = 0;
				} else if (preType == TYPE_SLASH) {
					token = cur - 1;
					preType = TYPE_DSLASH;
				} else {
					preType = TYPE_SLASH;
				}
			} else if (input[cur] == BACKSLASH) {
				preType = TYPE_BACKSLASH;
			} else if (input[cur] == STAR) {
				if (mark > 0)
					continue;
				if (preType == TYPE_SLASH) {
					token = cur - 1;
				}
				preType = TYPE_STAR;
			} else if (input[cur] == NEWLINE) {
				if (preType == TYPE_DSLASH) {
					input = del(input, token, cur - 1);
					cur = token - 1;
					preType = 0;
				}
			}

		}
		return new String(input);
	}

	public static char[] del(char[] _target, int _start, int _end) {
		char[] tmp = new char[_target.length - (_end - _start + 1)];
		System.arraycopy(_target, 0, tmp, 0, _start);
		System.arraycopy(_target, _end + 1, tmp, _start, _target.length - _end
				- 1);
		return tmp;
	}

	public static void main(String[] args) {
		try {
			System.setIn(new FileInputStream("/Users/litong/Desktop/a.in"));
			System.setOut(new PrintStream("/Users/litong/Desktop/a.out"));
			Scanner sc = new Scanner(System.in);
			StringBuilder sb = new StringBuilder();
			while (sc.hasNext()) {
				sb.append(sc.nextLine());
			}
			System.out.println(removeComment(sb.toString()));
		} catch (Exception e) {

		}
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值