1 41 package org.jfree.util; 42 43 import java.util.Iterator ; 44 45 51 public class LineBreakIterator implements Iterator 52 { 53 54 public static final int DONE = -1; 55 56 57 private char[] text; 58 59 60 private int position; 61 62 65 public LineBreakIterator() 66 { 67 setText(""); 68 } 69 70 75 public LineBreakIterator(final String text) 76 { 77 setText(text); 78 } 79 80 85 public synchronized int nextPosition() 86 { 87 if (this.text == null) 88 { 89 return DONE; 90 } 91 if (this.position == DONE) 92 { 93 return DONE; 94 } 95 96 98 final int nChars = this.text.length; 99 int nextChar = this.position; 100 101 for (;;) 102 { 103 if (nextChar >= nChars) 104 { 105 106 this.position = DONE; 107 return DONE; 108 } 109 110 boolean eol = false; 111 char c = 0; 112 int i; 113 114 for (i = nextChar; i < nChars; i++) 116 { 117 c = this.text[i]; 118 if ((c == '\n') || (c == '\r')) 119 { 120 eol = true; 121 break; 122 } 123 } 124 125 nextChar = i; 126 if (eol) 127 { 128 nextChar++; 129 if (c == '\r') 130 { 131 if ((nextChar < nChars) && (this.text[nextChar] == '\n')) 132 { 133 nextChar++; 134 } 135 } 136 this.position = nextChar; 137 return (this.position); 138 } 139 } 140 } 141 142 148 public int nextWithEnd() 149 { 150 final int pos = this.position; 151 if (pos == DONE) 152 { 153 return DONE; 154 } 155 if (pos == this.text.length) 156 { 157 this.position = DONE; 158 return DONE; 159 } 160 final int retval = nextPosition(); 161 if (retval == DONE) 162 { 163 return this.text.length; 164 } 165 return retval; 166 } 167 168 173 public String getText() 174 { 175 return new String (this.text); 176 } 177 178 183 public void setText(final String text) 184 { 185 this.position = 0; 186 this.text = text.toCharArray(); 187 } 188 189 196 public boolean hasNext() 197 { 198 return (this.position != DONE); 199 } 200 201 206 public Object next() 207 { 208 if (this.position == DONE) 209 { 210 return null; 212 } 213 214 final int lastFound = this.position; 215 int pos = nextWithEnd(); 216 if (pos == DONE) 217 { 218 return new String (this.text, lastFound, this.text.length - lastFound); 220 } 221 222 if (pos > 0) 224 { 225 final int end = lastFound; 226 for (; ((pos) > end) && ((this.text[pos - 1] == '\n') || this.text[pos - 1] == '\r'); pos--) 227 { 228 } 230 } 231 return new String (this.text, lastFound, pos - lastFound); 234 } 235 236 251 public void remove() 252 { 253 throw new UnsupportedOperationException ("This iterator is read-only."); 254 } 255 } 256 | Popular Tags |