微软实习面试-删除一个JAVA文件的全部注释
描述:删除一个合法的JAVA文件的全部注释,注释以"//"或者"/* */"表示。
注意: 单引号或者双引号内的文字可能包括"//"或者"/* */",但不是注释的部分。
解法:读入文件后,一个字符一个字符的处理。
1 public void deleteAllComment(InputStream is) throws IOException {
2 int i = is.read();
3 while(i != -1) {
4 char c = (char)i;
5 if(c == '/') {
6 char j = (char)is.read();
7 if(j == '/') {
8 deleteThisLine(is);
9 } else if(j == '*') {
10 deleteUntilEnd(is);
11 }
12 } else if(c == '\'' || c == '"') {
13 echoString(is, c);
14 } else {
15 System.out.print(c);
16 }
17 i = is.read();
18 }
19 }
20
21 //删除以"//"开头的注释
22 private void deleteThisLine(InputStream is) throws IOException {
23 char i = (char)is.read();
24 char j = (char)is.read();
25 while(true) {
26 if(i == '\r' && j=='\n') {
27 break;
28 } else {
29 i = j;
30 j = (char)is.read();
31 }
32 }
33 }
34
35 //删除以"/* */"表示的注释
36 private void deleteUntilEnd(InputStream is) throws IOException {
37 char i = (char)is.read();
38 char j = (char)is.read();
39 while(true) {
40 if(i == '*' && j=='/') {
41 break;
42 } else {
43 i = j;
44 j = (char)is.read();
45 }
46 }
47 }
48
49 //原样输出单引号或者双引号中的内容
50 private void echoString(InputStream is, int start) throws IOException {
51 char end = (char)is.read();
52 while(end != start) {
53 System.out.print(end);
54 end = (char)is.read();
55 }
56 }