import java.util.*; public class CommentStripper { private StaticTransitionTable transitions; private StringBuilder sb; private int index; private int state; private final char EOF = '@'; public CommentStripper(String src) { sb = new StringBuilder(src); transitions = new StaticTransitionTable(7, new char[]{'/', '*', '\n'}); createTransitions(); } private void createTransitions() { newTransition(0, 1, '/'); newTransition(1, 3, '/'); newTransition(1, 4, '*'); newTransition(3, 2, '\n'); newTransition(4, 5, '*'); newTransition(5, 6, '/'); } private boolean newTransition(int state1, int state2, char symbol) { return transitions.newTransition(state1, state2, symbol); } public String strip() { runFSM(); return sb.toString(); } private void runFSM() { this.state = 0; char symbol = nextChar(); do { int next = nextState(state, symbol); transition(next); process(this.state); symbol = nextChar(); }while(symbol != EOF); } private void transition(int next) { if(next > -1) { this.state = next; } } private void process(int state) { //not in a comment if(state == 0 || state == 2) { ; }else { //in a comment, do action to the //character we just examined doAction(this.index-1); } //final state //comment replaced //start FSM at initial state if(state == 2 || state == 6) this.state = 0; } //Override this to do whatever //you want with the comment character //I just remove it and reset the current character index. private void doAction(int index) { sb.replace(index, index+1, ""); this.index--; } private int nextState(int state, char symbol) { return transitions.next(state, symbol); } private char nextChar() { if(this.index >= sb.length()) return EOF; return sb.charAt(this.index++); } }