8
|
1 package howtouse;
|
|
2
|
|
3
|
|
4 public class CharReader {
|
|
5
|
|
6 final static char EOFchar = (char) 0;
|
|
7
|
9
|
8 private String text;
|
|
9 private int textLength;
|
8
|
10 private int index;
|
|
11
|
|
12 private final char LBRANK = '[';
|
|
13 private final char RBRANK = ']';
|
|
14 private final char VERBAR = '|';
|
17
|
15 private final char COLON= ':';
|
8
|
16
|
|
17
|
|
18 CharReader() {
|
|
19 }
|
|
20
|
9
|
21 public void setText(String str) {
|
|
22 text = str;
|
|
23 textLength = text.length();
|
|
24 index = 0;
|
|
25 }
|
8
|
26
|
|
27
|
|
28 char nextChar() {
|
9
|
29 if (index < textLength)
|
|
30 return text.charAt(index++);
|
8
|
31
|
|
32 return EOFchar;
|
|
33
|
|
34 }
|
|
35
|
9
|
36 String getToken() {
|
8
|
37
|
|
38 int nextState = 1;
|
|
39
|
|
40 StringBuffer buf = new StringBuffer(256);
|
|
41 char ch;
|
|
42 int index = -1;
|
|
43 while (true) {
|
|
44 ch = nextChar();
|
|
45 if (ch == EOFchar) return null;
|
|
46 switch (nextState) {
|
|
47 case 1:
|
|
48 if (ch == LBRANK)
|
|
49 nextState = 2;
|
|
50 break;
|
|
51 case 2:
|
|
52 if (ch == LBRANK)
|
|
53 nextState = 3;
|
|
54 else
|
|
55 nextState = 1;
|
|
56 break;
|
|
57 case 3:
|
|
58 if (ch == RBRANK) {
|
|
59 nextState = 4;
|
|
60 } else if (ch == VERBAR) {
|
|
61 index = buf.length();
|
17
|
62 buf.append(ch);
|
|
63 return buf.substring(0,index);
|
|
64 } else if (ch == COLON) {
|
|
65 index = 0;
|
|
66 buf.delete(0,buf.length());
|
8
|
67 } else {
|
|
68 buf.append(ch);
|
|
69 }
|
|
70 break;
|
|
71 case 4:
|
|
72 if (ch == RBRANK) {
|
|
73 if (index == -1) {
|
|
74 return buf.toString();
|
|
75 } else{
|
|
76 return buf.substring(0,index);
|
|
77 }
|
|
78 } else {
|
9
|
79 return null;
|
8
|
80 }
|
|
81 }
|
|
82
|
|
83 }
|
|
84
|
|
85 }
|
|
86 }
|