Example usage for java.text BreakIterator preceding

List of usage examples for java.text BreakIterator preceding

Introduction

In this page you can find the example usage for java.text BreakIterator preceding.

Prototype

public int preceding(int offset) 

Source Link

Document

Returns the last boundary preceding the specified character offset.

Usage

From source file:org.yamj.common.tools.StringTools.java

/**
 * Check that the passed string is not longer than the required length and
 * trim it if necessary/*from   w w w  .j  av a  2 s. c  o  m*/
 *
 * @param sourceString The string to check
 * @param requiredLength The required length (Maximum)
 * @param trimToWord Trim the source string to the last space to avoid
 * partial words
 * @param endingSuffix The ending to append if the string is longer than the
 * required length
 * @return
 */
public static String trimToLength(String sourceString, int requiredLength, boolean trimToWord,
        String endingSuffix) {
    String changedString = sourceString.trim();

    if (StringUtils.isNotBlank(changedString)) {
        if (changedString.length() <= requiredLength) {
            // No need to do anything
            return changedString;
        } else if (trimToWord) {
            BreakIterator bi = BreakIterator.getWordInstance();
            bi.setText(changedString);
            int biLength = bi.preceding(requiredLength - endingSuffix.length());
            return changedString.substring(0, biLength).trim() + endingSuffix;
        } else {
            // We know that the source string is longer that the required length, so trim it to size
            return changedString.substring(0, requiredLength - endingSuffix.length()).trim() + endingSuffix;
        }
    }

    return changedString;
}

From source file:org.yamj.core.tools.StringTools.java

/**
 * Check that the passed string is not longer than the required length and trim it if necessary
 *
 * @param sourceString The string to check
 * @param requiredLength The required length (Maximum)
 * @param trimToWord Trim the source string to the last space to avoid partial words
 * @param endingSuffix The ending to append if the string is longer than the required length
 * @return// w w w.j av a 2 s.c  o m
 */
public static String trimToLength(String sourceString, int requiredLength, boolean trimToWord,
        String endingSuffix) {
    String changedString = sourceString.trim();

    if (StringUtils.isNotBlank(changedString)) {
        if (changedString.length() <= requiredLength) {
            // No need to do anything
            return changedString;
        } else {
            if (trimToWord) {
                BreakIterator bi = BreakIterator.getWordInstance();
                bi.setText(changedString);
                int biLength = bi.preceding(requiredLength - endingSuffix.length());
                return changedString.substring(0, biLength).trim() + endingSuffix;
            } else {
                // We know that the source string is longer that the required length, so trim it to size
                return changedString.substring(0, requiredLength - endingSuffix.length()).trim() + endingSuffix;
            }
        }
    }

    return changedString;
}

From source file:com.moviejukebox.tools.StringTools.java

/**
 * Check that the passed string is not longer than the required length and
 * trim it if necessary/*from   w  ww . j a  v a 2 s .  c  o m*/
 *
 * @param sourceString The string to check
 * @param requiredLength The required length (Maximum)
 * @param trimToWord Trim the source string to the last space to avoid
 * partial words
 * @param endingSuffix The ending to append if the string is longer than the
 * required length
 * @return
 */
public static String trimToLength(String sourceString, int requiredLength, boolean trimToWord,
        String endingSuffix) {
    String changedString = sourceString.trim();

    if (isValidString(changedString)) {
        if (changedString.length() <= requiredLength) {
            // No need to do anything
            return changedString;
        }

        if (trimToWord) {
            BreakIterator bi = BreakIterator.getWordInstance();
            bi.setText(changedString);
            int biLength = bi.preceding(requiredLength - endingSuffix.length() + 1);
            return changedString.substring(0, biLength).trim() + endingSuffix;
        }

        // We know that the source string is longer that the required length, so trim it to size
        return changedString.substring(0, requiredLength - endingSuffix.length()).trim() + endingSuffix;
    }

    return changedString;
}

From source file:org.eclipse.fx.core.text.TextUtil.java

/**
 * Find the start offset of the word/* www.j av a  2  s  . com*/
 *
 * @param content
 *            the content
 * @param offset
 *            the offset to start the search from
 * @param pointAsBoundary
 *            should the '.' treated as word boundary
 * @return the start offset or or {@link BreakIterator#DONE}
 */
public static int findWordStartOffset(IterableCharSequence content, int offset, boolean pointAsBoundary) {
    BreakIterator wordInstance = BreakIterator.getWordInstance();
    wordInstance.setText(content.getIterator());
    int rv = wordInstance.preceding(offset);

    if (rv != BreakIterator.DONE && pointAsBoundary) {
        String s = content.subSequence(rv, offset).toString();
        int idx = s.lastIndexOf('.');
        if (idx > 0) {
            rv += idx + 1;
        }

        // move before the point
        if (rv == offset) {
            rv -= 1;
        }
    }

    return rv;
}

From source file:org.eclipse.fx.core.text.TextUtil.java

/**
 * Find the bounds of the word//from  w  w  w  .ja  va  2 s.  co  m
 *
 * @param content
 *            the content
 * @param offset
 *            the offset
 * @param pointAsBoundary
 *            should the '.' treated as word boundary
 * @return a tuple of value representing start and end
 */
public static IntTuple findWordBounds(IterableCharSequence content, int offset, boolean pointAsBoundary) {
    BreakIterator wordInstance = BreakIterator.getWordInstance();
    wordInstance.setText(content.getIterator());
    int previous = wordInstance.preceding(offset);
    int next = wordInstance.following(offset);

    if (pointAsBoundary && previous != BreakIterator.DONE && next != BreakIterator.DONE) {
        String preMatch = content.subSequence(previous, offset).toString();
        String postMatch = content.subSequence(offset, next).toString();

        int idx = preMatch.lastIndexOf('.');
        if (idx > 0) {
            previous += idx + 1;
        }

        idx = postMatch.indexOf('.');
        if (idx > 0) {
            next = offset + idx;
        }
    }

    return new IntTuple(previous, next);
}

From source file:StringUtils.java

/**
 * Reformats a string where lines that are longer than <tt>width</tt>
 * are split apart at the earliest wordbreak or at maxLength, whichever is
 * sooner. If the width specified is less than 5 or greater than the input
 * Strings length the string will be returned as is.
 * <p/>/*from   ww  w  . j  a v a 2s .c  o m*/
 * Please note that this method can be lossy - trailing spaces on wrapped
 * lines may be trimmed.
 *
 * @param input the String to reformat.
 * @param width the maximum length of any one line.
 * @return a new String with reformatted as needed.
 */
public static String wordWrap(String input, int width, Locale locale) {
    // protect ourselves
    if (input == null) {
        return "";
    } else if (width < 5) {
        return input;
    } else if (width >= input.length()) {
        return input;
    }

    StringBuilder buf = new StringBuilder(input);
    boolean endOfLine = false;
    int lineStart = 0;

    for (int i = 0; i < buf.length(); i++) {
        if (buf.charAt(i) == '\n') {
            lineStart = i + 1;
            endOfLine = true;
        }

        // handle splitting at width character
        if (i > lineStart + width - 1) {
            if (!endOfLine) {
                int limit = i - lineStart - 1;
                BreakIterator breaks = BreakIterator.getLineInstance(locale);
                breaks.setText(buf.substring(lineStart, i));
                int end = breaks.last();

                // if the last character in the search string isn't a space,
                // we can't split on it (looks bad). Search for a previous
                // break character
                if (end == limit + 1) {
                    if (!Character.isWhitespace(buf.charAt(lineStart + end))) {
                        end = breaks.preceding(end - 1);
                    }
                }

                // if the last character is a space, replace it with a \n
                if (end != BreakIterator.DONE && end == limit + 1) {
                    buf.replace(lineStart + end, lineStart + end + 1, "\n");
                    lineStart = lineStart + end;
                }
                // otherwise, just insert a \n
                else if (end != BreakIterator.DONE && end != 0) {
                    buf.insert(lineStart + end, '\n');
                    lineStart = lineStart + end + 1;
                } else {
                    buf.insert(i, '\n');
                    lineStart = i + 1;
                }
            } else {
                buf.insert(i, '\n');
                lineStart = i + 1;
                endOfLine = false;
            }
        }
    }

    return buf.toString();
}

From source file:com.amazon.android.ui.widget.EllipsizedTextView.java

/**
 * Find the first word/character break index before ellipsisIndex.
 *///from w ww.  j  ava2  s . c  o m
private int breakBefore(final String displayText, final int ellipsisIndex, final BreakIterator iterator) {

    iterator.setText(displayText);
    return iterator.preceding(ellipsisIndex);
}

From source file:net.bible.service.device.speak.SpeakTextProvider.java

private StartPos getPrevTextStartPos(String text, float fraction) {
    StartPos retVal = new StartPos();

    int allTextLength = text.length();
    int nextTextOffset = (int) (Math.min(1, fraction) * allTextLength);

    BreakIterator breakIterator = BreakIterator.getSentenceInstance();
    breakIterator.setText(text);//from   w w  w  .  j av  a2 s  .  co  m
    int startPos = 0;
    try {
        // this can rarely throw an Exception
        startPos = breakIterator.preceding(nextTextOffset);
    } catch (Exception e) {
        Log.e(TAG, "Error finding previous sentence start", e);
    }
    retVal.found = startPos >= 0;

    if (retVal.found) {
        retVal.startPosition = startPos;

        // because we don't return an exact fraction, but go to the beginning of a sentence, we need to update the fractionAlreadySpoken  
        retVal.actualFractionOfWhole = ((float) retVal.startPosition) / allTextLength;

        retVal.text = text.substring(retVal.startPosition);
    }

    return retVal;
}

From source file:com.bellman.bible.service.device.speak.SpeakTextProvider.java

private StartPos getPrevTextStartPos(String text, float fraction) {
    StartPos retVal = new StartPos();

    int allTextLength = text.length();
    int nextTextOffset = (int) (Math.min(1, fraction) * allTextLength);

    BreakIterator breakIterator = BreakIterator.getSentenceInstance();
    breakIterator.setText(text);//w w  w.  ja  va 2s.  c  o m
    int startPos = 0;
    try {
        // this can rarely throw an Exception
        startPos = breakIterator.preceding(nextTextOffset);
    } catch (Exception e) {
        Log.e(TAG, "Error finding previous sentence start", e);
    }
    retVal.found = startPos >= 0;

    if (retVal.found) {
        retVal.startPosition = startPos;

        // because we don't return an exact fraction, but go to the beginning of a sentence, we need to update the fractionAlreadySpoken
        retVal.actualFractionOfWhole = ((float) retVal.startPosition) / allTextLength;

        retVal.text = text.substring(retVal.startPosition);
    }

    return retVal;
}

From source file:org.jivesoftware.util.StringUtils.java

/**
 * Reformats a string where lines that are longer than <tt>width</tt>
 * are split apart at the earliest wordbreak or at maxLength, whichever is
 * sooner. If the width specified is less than 5 or greater than the input
 * Strings length the string will be returned as is.
 * <p>/*from ww  w  .  j  a  v a 2s .c om*/
 * Please note that this method can be lossy - trailing spaces on wrapped
 * lines may be trimmed.</p>
 *
 * @param input the String to reformat.
 * @param width the maximum length of any one line.
 * @return a new String with reformatted as needed.
 */
public static String wordWrap(String input, int width, Locale locale) {
    // protect ourselves
    if (input == null) {
        return "";
    } else if (width < 5) {
        return input;
    } else if (width >= input.length()) {
        return input;
    }

    // default locale
    if (locale == null) {
        locale = JiveGlobals.getLocale();
    }

    StringBuilder buf = new StringBuilder(input);
    boolean endOfLine = false;
    int lineStart = 0;

    for (int i = 0; i < buf.length(); i++) {
        if (buf.charAt(i) == '\n') {
            lineStart = i + 1;
            endOfLine = true;
        }

        // handle splitting at width character
        if (i > lineStart + width - 1) {
            if (!endOfLine) {
                int limit = i - lineStart - 1;
                BreakIterator breaks = BreakIterator.getLineInstance(locale);
                breaks.setText(buf.substring(lineStart, i));
                int end = breaks.last();

                // if the last character in the search string isn't a space,
                // we can't split on it (looks bad). Search for a previous
                // break character
                if (end == limit + 1) {
                    if (!Character.isWhitespace(buf.charAt(lineStart + end))) {
                        end = breaks.preceding(end - 1);
                    }
                }

                // if the last character is a space, replace it with a \n
                if (end != BreakIterator.DONE && end == limit + 1) {
                    buf.replace(lineStart + end, lineStart + end + 1, "\n");
                    lineStart = lineStart + end;
                }
                // otherwise, just insert a \n
                else if (end != BreakIterator.DONE && end != 0) {
                    buf.insert(lineStart + end, '\n');
                    lineStart = lineStart + end + 1;
                } else {
                    buf.insert(i, '\n');
                    lineStart = i + 1;
                }
            } else {
                buf.insert(i, '\n');
                lineStart = i + 1;
                endOfLine = false;
            }
        }
    }

    return buf.toString();
}