下面列出了怎么用java.text.CharacterIterator的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Escape characters for text appearing as XML data, between tags.
*
* <P>The following characters are replaced with corresponding character entities :
* <table border='1' cellpadding='3' cellspacing='0'>
* <tr><th> Character </th><th> Encoding </th></tr>
* <tr><td> < </td><td> < </td></tr>
* <tr><td> > </td><td> > </td></tr>
* <tr><td> & </td><td> & </td></tr>
* <tr><td> " </td><td> "</td></tr>
* <tr><td> ' </td><td> '</td></tr>
* </table>
*
* <P>Note that JSTL's {@code <c:out>} escapes the exact same set of
* characters as this method. <span class='highlight'>That is, {@code <c:out>}
* is good for escaping to produce valid XML, but not for producing safe
* HTML.</span>
*/
public static String forXML(String aText) {
if (aText == null) return null;
final StringBuilder result = new StringBuilder();
final StringCharacterIterator iterator = new StringCharacterIterator(aText);
char character = iterator.current();
while (character != CharacterIterator.DONE) {
if (character == '<') {
result.append("<");
} else if (character == '>') {
result.append(">");
} else if (character == '\"') {
result.append(""");
} else if (character == '\'') {
result.append("'");
} else if (character == '&') {
result.append("&");
} else {
//the char is not a special one
//add it to the result as is
result.append(character);
}
character = iterator.next();
}
return result.toString();
}
/**
* Set the target text to be searched. Text iteration will then begin at
* the start of the text string. This method is useful if you want to
* reuse an iterator to search within a different body of text.
*
* @param text new text iterator to look for match,
* @exception IllegalArgumentException thrown when text is null or has
* 0 length
* @see #getTarget
* @stable ICU 2.4
*/
public void setTarget(CharacterIterator text)
{
if (text == null || text.getEndIndex() == text.getIndex()) {
throw new IllegalArgumentException("Illegal null or empty text");
}
text.setIndex(text.getBeginIndex());
search_.setTarget(text);
search_.matchedIndex_ = DONE;
search_.setMatchedLength(0);
search_.reset_ = true;
search_.isForwardSearching_ = true;
if (search_.breakIter() != null) {
// Create a clone of CharacterItearator, so it won't
// affect the position currently held by search_.text()
search_.breakIter().setText((CharacterIterator)text.clone());
}
if (search_.internalBreakIter_ != null) {
search_.internalBreakIter_.setText((CharacterIterator)text.clone());
}
}
private static final void checkIteratorText(AttributedCharacterIterator iterator, String expectedText) throws Exception {
if (iterator.getEndIndex() - iterator.getBeginIndex() != expectedText.length()) {
throwException(iterator, "text length doesn't match between original text and iterator");
}
char c = iterator.first();
for (int i = 0; i < expectedText.length(); i++) {
if (c != expectedText.charAt(i)) {
throwException(iterator, "text content doesn't match between original text and iterator");
}
c = iterator.next();
}
if (c != CharacterIterator.DONE) {
throwException(iterator, "iterator text doesn't end with DONE");
}
}
/**
* Advances the iterator one step backwards.
* @return The position of the last boundary position before the
* current iteration position
*/
@Override
public int previous() {
CharacterIterator text = getText();
// if we have cached break positions and we're still in the range
// covered by them, just move one step backward in the cache
if (cachedBreakPositions != null && positionInCache > 0) {
--positionInCache;
text.setIndex(cachedBreakPositions[positionInCache]);
return cachedBreakPositions[positionInCache];
}
// otherwise, dump the cache and use the inherited previous() method to move
// backward. This may fill up the cache with new break positions, in which
// case we have to mark our position in the cache
else {
cachedBreakPositions = null;
int result = super.previous();
if (cachedBreakPositions != null) {
positionInCache = cachedBreakPositions.length - 2;
}
return result;
}
}
private static AttributedCharacterIterator getTrimmedTrailingSpacesIterator
(AttributedCharacterIterator iterator) {
int curIdx = iterator.getIndex();
char c = iterator.last();
while(c != CharacterIterator.DONE && Character.isWhitespace(c)) {
c = iterator.previous();
}
if (c != CharacterIterator.DONE) {
int endIdx = iterator.getIndex();
if (endIdx == iterator.getEndIndex() - 1) {
iterator.setIndex(curIdx);
return iterator;
} else {
AttributedString trimmedText = new AttributedString(iterator,
iterator.getBeginIndex(), endIdx + 1);
return trimmedText.getIterator();
}
} else {
return null;
}
}
private boolean valid(String input) {
if ("".equals(input)) return true;
boolean ret = true;
it = new StringCharacterIterator(input);
c = it.first();
col = 1;
if (!value()) {
ret = error("value", 1);
} else {
skipWhiteSpace();
if (c != CharacterIterator.DONE) {
ret = error("end", col);
}
}
return ret;
}
private boolean literal(String text) {
CharacterIterator ci = new StringCharacterIterator(text);
char t = ci.first();
if (c != t) { return false; }
int start = col;
boolean ret = true;
for (t = ci.next(); t != CharacterIterator.DONE; t = ci.next()) {
if (t != nextCharacter()) {
ret = false;
break;
}
}
nextCharacter();
if (!ret) { error("literal " + text, start); }
return ret;
}
public static int append(Appendable result, CharacterIterator iterator) {
try {
int start = iterator.getBeginIndex();
int limit = iterator.getEndIndex();
int length = limit - start;
if (start < limit) {
result.append(iterator.first());
while (++start < limit) {
result.append(iterator.next());
}
}
return length;
} catch(IOException e) {
throw new ICUUncheckedIOException(e);
}
}
private boolean literal(String text) {
CharacterIterator ci = new StringCharacterIterator(text);
char t = ci.first();
if (c != t) return false;
int start = col;
boolean ret = true;
for (t = ci.next(); t != CharacterIterator.DONE; t = ci.next()) {
if (t != nextCharacter()) {
ret = false;
break;
}
}
nextCharacter();
if (!ret) error("literal " + text, start);
return ret;
}
private static final void checkIteratorText(AttributedCharacterIterator iterator, String expectedText) throws Exception {
if (iterator.getEndIndex() - iterator.getBeginIndex() != expectedText.length()) {
throwException(iterator, "text length doesn't match between original text and iterator");
}
char c = iterator.first();
for (int i = 0; i < expectedText.length(); i++) {
if (c != expectedText.charAt(i)) {
throwException(iterator, "text content doesn't match between original text and iterator");
}
c = iterator.next();
}
if (c != CharacterIterator.DONE) {
throwException(iterator, "iterator text doesn't end with DONE");
}
}
/**
* Indicates whether or not this <code>Font</code> can display the
* text specified by the <code>iter</code> starting at
* <code>start</code> and ending at <code>limit</code>.
*
* @param iter a {@link CharacterIterator} object
* @param start the specified starting offset into the specified
* <code>CharacterIterator</code>.
* @param limit the specified ending offset into the specified
* <code>CharacterIterator</code>.
* @return an offset into <code>iter</code> that points
* to the first character in <code>iter</code> that this
* <code>Font</code> cannot display; or <code>-1</code> if
* this <code>Font</code> can display all characters in
* <code>iter</code>.
* @since 1.2
*/
public int canDisplayUpTo(CharacterIterator iter, int start, int limit) {
Font2D font2d = getFont2D();
char c = iter.setIndex(start);
for (int i = start; i < limit; i++, c = iter.next()) {
if (font2d.canDisplay(c)) {
continue;
}
if (!Character.isHighSurrogate(c)) {
return i;
}
char c2 = iter.next();
// c2 could be CharacterIterator.DONE which is not a low surrogate.
if (!Character.isLowSurrogate(c2)) {
return i;
}
if (!font2d.canDisplay(Character.toCodePoint(c, c2))) {
return i;
}
i++;
}
return -1;
}
@Override
public Object clone() {
SafeCharIterator copy = null;
try {
copy = (SafeCharIterator) super.clone();
}
catch(CloneNotSupportedException e) {
throw new Error("Clone not supported: " + e);
}
CharacterIterator copyOfBase = (CharacterIterator) base.clone();
copy.base = copyOfBase;
return copy;
}
/**
* Sets the current iteration position to the last boundary position
* before the specified position.
* @param offset The position to begin searching from
* @return The position of the last boundary before "offset"
*/
@Override
public int preceding(int offset) {
CharacterIterator text = getText();
checkOffset(offset, text);
// if we have no cached break positions, or "offset" is outside the
// range covered by the cache, we can just call the inherited routine
// (which will eventually call other routines in this class that may
// refresh the cache)
if (cachedBreakPositions == null || offset <= cachedBreakPositions[0] ||
offset > cachedBreakPositions[cachedBreakPositions.length - 1]) {
cachedBreakPositions = null;
return super.preceding(offset);
}
// on the other hand, if "offset" is within the range covered by the cache,
// then all we have to do is search the cache for the last break position
// before "offset"
else {
positionInCache = 0;
while (positionInCache < cachedBreakPositions.length
&& offset > cachedBreakPositions[positionInCache]) {
++positionInCache;
}
--positionInCache;
text.setIndex(cachedBreakPositions[positionInCache]);
return text.getIndex();
}
}
@Override
public void setText(CharacterIterator newText) {
super.setText(newText);
cachedBreakPositions = null;
dictionaryCharCount = 0;
positionInCache = 0;
}
private static int codePointBefore(CharacterIterator iter, int index) {
int currentIterIndex = iter.getIndex();
iter.setIndex(index);
char codeUnit = iter.previous();
int cp = codeUnit;
if (Character.isLowSurrogate(codeUnit)) {
char prevUnit = iter.previous();
if (Character.isHighSurrogate(prevUnit)) {
cp = Character.toCodePoint(prevUnit, codeUnit);
}
}
iter.setIndex(currentIterIndex); // restore iter position
return cp;
}
/**
* Creates a clone of this iterator. Clones the underlying character iterator.
* @see UCharacterIterator#clone()
*/
public Object clone(){
try {
CharacterIteratorWrapper result = (CharacterIteratorWrapper) super.clone();
result.iterator = (CharacterIterator)this.iterator.clone();
return result;
} catch (CloneNotSupportedException e) {
return null; // only invoked if bad underlying character iterator
}
}
public void testBasicUsage() {
CharArrayIterator ci = new CharArrayIterator();
ci.setText("testing".toCharArray(), 0, "testing".length());
assertEquals(0, ci.getBeginIndex());
assertEquals(7, ci.getEndIndex());
assertEquals(0, ci.getIndex());
assertEquals('t', ci.current());
assertEquals('e', ci.next());
assertEquals('g', ci.last());
assertEquals('n', ci.previous());
assertEquals('t', ci.first());
assertEquals(CharacterIterator.DONE, ci.previous());
}
/**
* Sets the current iteration position to the beginning of the text.
* (i.e., the CharacterIterator's starting offset).
* @return The offset of the beginning of the text.
*/
@Override
public int first() {
CharacterIterator t = getText();
t.first();
return t.getIndex();
}
@Override
String format(
AttributedCharacterIterator iterator,
String preExponent) {
int copyFromOffset = 0;
StringBuilder result = new StringBuilder();
for (
iterator.first();
iterator.current() != CharacterIterator.DONE;
) {
Map<Attribute, Object> attributeSet = iterator.getAttributes();
if (attributeSet.containsKey(NumberFormat.Field.EXPONENT_SYMBOL)) {
append(
iterator,
copyFromOffset,
iterator.getRunStart(NumberFormat.Field.EXPONENT_SYMBOL),
result);
copyFromOffset = iterator.getRunLimit(NumberFormat.Field.EXPONENT_SYMBOL);
iterator.setIndex(copyFromOffset);
result.append(preExponent);
result.append(beginMarkup);
} else if (attributeSet.containsKey(NumberFormat.Field.EXPONENT)) {
int limit = iterator.getRunLimit(NumberFormat.Field.EXPONENT);
append(
iterator,
copyFromOffset,
limit,
result);
copyFromOffset = limit;
iterator.setIndex(copyFromOffset);
result.append(endMarkup);
} else {
iterator.next();
}
}
append(iterator, copyFromOffset, iterator.getEndIndex(), result);
return result.toString();
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final CharacterIterator ci = tcctx.ci;
final FontRenderContext frc = tcctx.frc;
GlyphVector gv;
do {
gv = font.createGlyphVector(frc, ci);
} while (--numReps >= 0);
}
/**
* Set the iterator to analyze a new piece of text. This function resets
* the current iteration position to the beginning of the text.
* @param newText An iterator over the text to analyze.
*/
@Override
public void setText(CharacterIterator newText) {
// Test iterator to see if we need to wrap it in a SafeCharIterator.
// The correct behavior for CharacterIterators is to allow the
// position to be set to the endpoint of the iterator. Many
// CharacterIterators do not uphold this, so this is a workaround
// to permit them to use this class.
int end = newText.getEndIndex();
boolean goodIterator;
try {
newText.setIndex(end); // some buggy iterators throw an exception here
goodIterator = newText.getIndex() == end;
}
catch(IllegalArgumentException e) {
goodIterator = false;
}
if (goodIterator) {
text = newText;
}
else {
text = new SafeCharIterator(newText);
}
text.first();
cachedLastKnownBreak = BreakIterator.DONE;
}
/**
* Clones this iterator.
* @return A newly-constructed RuleBasedBreakIterator with the same
* behavior as this one.
*/
@Override
public Object clone() {
RuleBasedBreakIterator result = (RuleBasedBreakIterator) super.clone();
if (text != null) {
result.text = (CharacterIterator) text.clone();
}
return result;
}
/**
* Set the iterator to analyze a new piece of text. This function resets
* the current iteration position to the beginning of the text.
* @param newText An iterator over the text to analyze.
*/
@Override
public void setText(CharacterIterator newText) {
// Test iterator to see if we need to wrap it in a SafeCharIterator.
// The correct behavior for CharacterIterators is to allow the
// position to be set to the endpoint of the iterator. Many
// CharacterIterators do not uphold this, so this is a workaround
// to permit them to use this class.
int end = newText.getEndIndex();
boolean goodIterator;
try {
newText.setIndex(end); // some buggy iterators throw an exception here
goodIterator = newText.getIndex() == end;
}
catch(IllegalArgumentException e) {
goodIterator = false;
}
if (goodIterator) {
text = newText;
}
else {
text = new SafeCharIterator(newText);
}
text.first();
cachedLastKnownBreak = BreakIterator.DONE;
}
/**
* @see UCharacterIterator#current()
*/
public int current() {
int c = iterator.current();
if(c==CharacterIterator.DONE){
return DONE;
}
return c;
}
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, int[] expectedLimits) throws Exception {
int previous = 0;
char c = iterator.first();
for (int i = 0; i < expectedLimits.length; i++) {
if (iterator.getRunStart() != previous || iterator.getRunLimit() != expectedLimits[i]) {
throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart() + ", " + iterator.getRunLimit());
}
previous = expectedLimits[i];
c = iterator.setIndex(previous);
}
if (c != CharacterIterator.DONE) {
throwException(iterator, "iterator's run sequence doesn't end with DONE");
}
}
/**
* @see UCharacterIterator#previous()
*/
public int previous() {
int i = iterator.previous();
if(i==CharacterIterator.DONE){
return DONE;
}
return i;
}
/**
* Sets the current iteration position to the beginning of the text.
* (i.e., the CharacterIterator's starting offset).
* @return The offset of the beginning of the text.
*/
@Override
public int first() {
CharacterIterator t = getText();
t.first();
return t.getIndex();
}
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, int[] expectedLimits) throws Exception {
int previous = 0;
char c = iterator.first();
for (int i = 0; i < expectedLimits.length; i++) {
if (iterator.getRunStart() != previous || iterator.getRunLimit() != expectedLimits[i]) {
throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart() + ", " + iterator.getRunLimit());
}
previous = expectedLimits[i];
c = iterator.setIndex(previous);
}
if (c != CharacterIterator.DONE) {
throwException(iterator, "iterator's run sequence doesn't end with DONE");
}
}
/**
* Set the iterator to analyze a new piece of text. This function resets
* the current iteration position to the beginning of the text.
* @param newText An iterator over the text to analyze.
*/
@Override
public void setText(CharacterIterator newText) {
// Test iterator to see if we need to wrap it in a SafeCharIterator.
// The correct behavior for CharacterIterators is to allow the
// position to be set to the endpoint of the iterator. Many
// CharacterIterators do not uphold this, so this is a workaround
// to permit them to use this class.
int end = newText.getEndIndex();
boolean goodIterator;
try {
newText.setIndex(end); // some buggy iterators throw an exception here
goodIterator = newText.getIndex() == end;
}
catch(IllegalArgumentException e) {
goodIterator = false;
}
if (goodIterator) {
text = newText;
}
else {
text = new SafeCharIterator(newText);
}
text.first();
cachedLastKnownBreak = BreakIterator.DONE;
}
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, Attribute key, int[] expectedLimits) throws Exception {
int previous = 0;
char c = iterator.first();
for (int i = 0; i < expectedLimits.length; i++) {
if (iterator.getRunStart(key) != previous || iterator.getRunLimit(key) != expectedLimits[i]) {
throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart(key) + ", " + iterator.getRunLimit(key) + " for key " + key);
}
previous = expectedLimits[i];
c = iterator.setIndex(previous);
}
if (c != CharacterIterator.DONE) {
throwException(iterator, "iterator's run sequence doesn't end with DONE");
}
}