Example usage for java.lang Character isWhitespace

List of usage examples for java.lang Character isWhitespace

Introduction

In this page you can find the example usage for java.lang Character isWhitespace.

Prototype

public static boolean isWhitespace(int codePoint) 

Source Link

Document

Determines if the specified character (Unicode code point) is white space according to Java.

Usage

From source file:henplus.commands.SQLCommand.java

/**
 * looks, if this word is contained in 'all', preceeded and followed by a whitespace.
 */// w  w w. j  a  va 2s .  c o m
private boolean containsWord(final String all, final String word) {
    final int wordLen = word.length();
    final int index = all.indexOf(word);
    return index >= 0 && (index == 0 || Character.isWhitespace(all.charAt(index - 1)))
            && Character.isWhitespace(all.charAt(index + wordLen));
}

From source file:com.moss.schematrax.SchemaUpdater.java

private String trimTrailingWhitespace(String string) {
    int position = string.length() - 1;
    while (position >= 0 && Character.isWhitespace(string.charAt(position)))
        position--;//from   w ww  . j a v  a 2s .c om
    return string.substring(0, position + 1);
}

From source file:ths.commons.util.StringUtils.java

/**
 * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
 *
 * <pre>/*from w ww .j  a v a2s .  co m*/
 * StringUtils.isBlank(null)      = true
 * StringUtils.isBlank("")        = true
 * StringUtils.isBlank(" ")       = true
 * StringUtils.isBlank("bob")     = false
 * StringUtils.isBlank("  bob  ") = false
 * </pre>
 *
 * @param cs  the CharSequence to check, may be null
 * @return {@code true} if the CharSequence is null, empty or whitespace
 */
public static boolean isBlank(CharSequence cs) {
    int strLen;
    if (cs == null || (strLen = cs.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if ((Character.isWhitespace(cs.charAt(i)) == false)) {
            return false;
        }
    }
    return true;
}

From source file:cc.kune.core.server.utils.StringW.java

/**
 * Word-wrap a string.// w w w.ja v  a  2 s  . c  o m
 * 
 * @param str
 *          String to word-wrap
 * @param width
 *          int to wrap at
 * @param delim
 *          String to use to separate lines
 * @param split
 *          String to use to split a word greater than width long
 * @param delimInside
 *          wheter or not delim should be included in chunk before length
 *          reaches width.
 * 
 * @return String that has been word wrapped
 */
// @PMD:REVIEWED:AvoidReassigningParameters: by vjrj on 21/05/09 14:13
static public String wordWrap(final String str, int width, final String delim, final String split,
        final boolean delimInside) {
    final int sz = str.length();

    // System.err.println( ">>>> inside: " + delimInside + " sz : " + sz );

    // / shift width up one. mainly as it makes the logic easier
    width++;

    // our best guess as to an initial size
    final StringBuffer buffer = new StringBuffer(sz / width * delim.length() + sz);

    // every line might include a delim on the end
    // System.err.println( "width before: "+ width );
    if (delimInside) {
        width = width - delim.length();
    } else {
        width--;
    }
    // System.err.println( "width after: "+ width );

    int idx = -1;
    String substr = null;

    // beware: i is rolled-back inside the loop
    for (int i = 0; i < sz; i += width) {

        // on the last line
        if (i > sz - width) {
            buffer.append(str.substring(i));
            // System.err.print("LAST-LINE: "+str.substring(i));
            break;
        }

        // System.err.println("loop[i] is: "+i);
        // the current line
        substr = str.substring(i, i + width);
        // System.err.println( "substr: " + substr );

        // is the delim already on the line
        idx = substr.indexOf(delim);
        // System.err.println( "i: " + i + " idx : " + idx );
        if (idx != -1) {
            buffer.append(substr.substring(0, idx));
            // System.err.println("Substr: '"substr.substring(0,idx)+"'");
            buffer.append(delim);
            i -= width - idx - delim.length();

            // System.err.println("loop[i] is now: "+i);
            // System.err.println("ounfd-whitespace: '"+substr.charAt(idx+1)+"'.");
            // Erase a space after a delim. Is this too obscure?
            if (substr.length() > idx + 1) {
                if (substr.charAt(idx + 1) != '\n') {
                    if (Character.isWhitespace(substr.charAt(idx + 1))) {
                        i++;
                    }
                }
            }
            // System.err.println("i -= "+width+"-"+idx);
            continue;
        }

        idx = -1;

        // figure out where the last space is
        final char[] chrs = substr.toCharArray();
        for (int j = width; j > 0; j--) {
            if (Character.isWhitespace(chrs[j - 1])) {
                idx = j;
                // System.err.println("Found whitespace: "+idx);
                break;
            }
        }

        // idx is the last whitespace on the line.
        // System.err.println("idx is "+idx);
        if (idx == -1) {
            for (int j = width; j > 0; j--) {
                if (chrs[j - 1] == '-') {
                    idx = j;
                    // System.err.println("Found Dash: "+idx);
                    break;
                }
            }
            if (idx == -1) {
                buffer.append(substr);
                buffer.append(delim);
                // System.err.print(substr);
                // System.err.print(delim);
            } else {
                if (idx != width) {
                    idx++;
                }
                buffer.append(substr.substring(0, idx));
                buffer.append(delim);
                // System.err.print(substr.substring(0,idx));
                // System.err.print(delim);
                i -= width - idx;
            }
        } else {
            /*
             * if(force) { if(idx == width-1) { buffer.append(substr);
             * buffer.append(delim); } else { // stick a split in. int splitsz =
             * split.length(); buffer.append(substr.substring(0,width-splitsz));
             * buffer.append(split); buffer.append(delim); i -= splitsz; } } else {
             */
            // insert spaces
            buffer.append(substr.substring(0, idx));
            buffer.append(StringUtils.repeat(" ", width - idx));
            // System.err.print(substr.substring(0,idx));
            // System.err.print(StringUtils.repeat(" ",width-idx));
            buffer.append(delim);
            // System.err.print(delim);
            // System.err.println("i -= "+width+"-"+idx);
            i -= width - idx;
            // }
        }
    }
    // System.err.println("\n*************");
    return buffer.toString();
}

From source file:com.safi.workshop.sqlexplorer.parsers.BasicQueryParser.java

/**
 * Gets the next query, or returns null if there are no more
 * /*from   ww w.  j  a  v  a  2  s  .co  m*/
 * @return
 */
private BasicQuery getNextQuery() {
    if (charIndex >= sql.length())
        return null;

    int start = charIndex;
    int startOfLine = -1;
    char cQuote = 0;
    boolean inSLComment = false;
    boolean inMLComment = false;
    int startLineNo = -1;
    for (; charIndex < sql.length(); charIndex++) {
        char c = sql.charAt(charIndex);
        char nextC = 0;
        if (charIndex < sql.length() - 1)
            nextC = sql.charAt(charIndex + 1);

        // Skip comments
        if (inSLComment) {
            if (c == '\n') {
                inSLComment = false;
            } else {
                continue;
            }
        }
        if (inMLComment) {
            if (c == '\n') {
                startOfLine = -1;
                lineNo++;
            }
            inMLComment = !nextIs(mlCommentEnd);
            continue;
        }
        // If we're quoting
        if (cQuote != 0) {
            if (c == quoteEscapes && QUOTE_CHARS.indexOf(nextC) > -1)
                charIndex++;
            else if (cQuote == c)
                cQuote = 0;
            continue;
        }

        // Skip leading whitespace
        if (start == charIndex && Character.isWhitespace(c)) {
            start++;
            if (c == '\n') {
                startOfLine = -1;
                lineNo++;
            }
            continue;
        }
        // Calculate the start of line (gets reset to -1 on every \n)
        if (startOfLine < 0 && !Character.isWhitespace(c))
            startOfLine = charIndex;

        if (cmdSeparator != null && nextIs(cmdSeparator)) {
            int oldCharIndex = charIndex;
            charIndex += cmdSeparator.length();
            if (startLineNo < 0 || start + cmdSeparator.length() >= oldCharIndex) {
                start = charIndex;
                startLineNo = -1;
                startOfLine = -1;
                continue;
            }
            CharSequence qry = sql.subSequence(start, oldCharIndex);
            Set<com.safi.workshop.sqlexplorer.parsers.QueryParameter> parms = null;
            try {
                parms = parseArgs(qry.toString());
            } catch (ParserException e) {
                e.printStackTrace();
                MessageDialog.openError(SafiWorkshopEditorUtil.getActiveShell(), "Parse Param Error",
                        "Error caught while parsing parameters: " + e.getLocalizedMessage());
                return null;
            }

            BasicQuery bq = new BasicQuery(qry, startLineNo);
            bq.setQueryParameters((LinkedHashSet<com.safi.workshop.sqlexplorer.parsers.QueryParameter>) parms);
            return bq;
            // return new BasicQuery(sql.subSequence(start, oldCharIndex), startLineNo);
        }
        // Starting a quote?
        if (QUOTE_CHARS.indexOf(c) > -1) {
            cQuote = c;
            continue;
        }

        // Newlines - count line numbers, and look for "GO" (or equivelant)
        if (c == '\n') {
            if (rangeIs(startOfLine, charIndex, altSeparator)) {
                if (startLineNo < 0 || start + altSeparator.length() >= startOfLine) {
                    start = charIndex + 1;
                    startLineNo = -1;
                    startOfLine = -1;
                    lineNo++;
                    continue;
                }

                CharSequence qry = sql.subSequence(start, startOfLine);
                Set<com.safi.workshop.sqlexplorer.parsers.QueryParameter> parms = null;
                try {
                    parms = parseArgs(qry.toString());
                } catch (ParserException e) {
                    e.printStackTrace();
                    MessageDialog.openError(SafiWorkshopEditorUtil.getActiveShell(), "Parse Param Error",
                            "Error caught while parsing parameters: " + e.getLocalizedMessage());
                    return null;
                }

                BasicQuery bq = new BasicQuery(qry, startLineNo);
                bq.setQueryParameters(
                        (LinkedHashSet<com.safi.workshop.sqlexplorer.parsers.QueryParameter>) parms);
                return bq;
            }
            if (startOfLine >= 0) {
                String lineStart = sql.subSequence(startOfLine, Math.min(charIndex, startOfLine + 15))
                        .toString().toLowerCase();
                if (lineStart.startsWith("delimiter")) {
                    String delimiter = lineStart.substring(9).trim();
                    if (delimiter.length() == 1) {
                        setCmdSeparator(delimiter);
                        setAltSeparator(null);
                    } else {
                        setCmdSeparator(new String(new byte[] { 0 }));
                        setAltSeparator(delimiter);
                    }
                    if (startLineNo < 0 || start + lineStart.length() >= startOfLine) {
                        start = charIndex + 1;
                        startLineNo = -1;
                        startOfLine = -1;
                        lineNo++;
                        continue;
                    }

                    CharSequence qry = sql.subSequence(start, startOfLine);
                    Set<com.safi.workshop.sqlexplorer.parsers.QueryParameter> parms = null;
                    try {
                        parms = parseArgs(qry.toString());
                    } catch (ParserException e) {
                        e.printStackTrace();
                        MessageDialog.openError(SafiWorkshopEditorUtil.getActiveShell(), "Parse Param Error",
                                "Error caught while parsing parameters: " + e.getLocalizedMessage());
                        return null;
                    }

                    BasicQuery bq = new BasicQuery(qry, startLineNo);
                    bq.setQueryParameters(
                            (LinkedHashSet<com.safi.workshop.sqlexplorer.parsers.QueryParameter>) parms);
                    return bq;
                    // return new BasicQuery(sql.subSequence(start, startOfLine), startLineNo);
                }
            }
            startOfLine = -1;
            lineNo++;
            if (inSLComment) {
                inSLComment = false;
                continue;
            }
        }

        // Starting a single-line comment
        if (nextIs(slComment)) {
            if (rangeIs(startOfLine, charIndex, altSeparator)) {
                if (startLineNo < 0 || start + altSeparator.length() >= startOfLine) {
                    start = charIndex;
                    startLineNo = -1;
                    startOfLine = -1;
                    continue;
                }

                CharSequence qry = sql.subSequence(start, startOfLine);
                Set<com.safi.workshop.sqlexplorer.parsers.QueryParameter> parms = null;
                try {
                    parms = parseArgs(qry.toString());
                } catch (ParserException e) {
                    e.printStackTrace();
                    MessageDialog.openError(SafiWorkshopEditorUtil.getActiveShell(), "Parse Param Error",
                            "Error caught while parsing parameters: " + e.getLocalizedMessage());
                    return null;
                }

                BasicQuery bq = new BasicQuery(qry, startLineNo);
                bq.setQueryParameters(
                        (LinkedHashSet<com.safi.workshop.sqlexplorer.parsers.QueryParameter>) parms);
                return bq;

                // return new BasicQuery(sql.subSequence(start, startOfLine), startLineNo);
            }
            inSLComment = true;
            continue;
        }

        // Starting a multi-line comment
        if (nextIs(mlCommentStart)) {
            if (rangeIs(startOfLine, charIndex, altSeparator)) {
                if (startLineNo < 0 || start + altSeparator.length() >= startOfLine) {
                    start = charIndex;
                    startLineNo = -1;
                    startOfLine = -1;
                    continue;
                }
                CharSequence qry = sql.subSequence(start, startOfLine);
                Set<com.safi.workshop.sqlexplorer.parsers.QueryParameter> parms = null;
                try {
                    parms = parseArgs(qry.toString());
                } catch (ParserException e) {
                    e.printStackTrace();
                    MessageDialog.openError(SafiWorkshopEditorUtil.getActiveShell(), "Parse Param Error",
                            "Error caught while parsing parameters: " + e.getLocalizedMessage());
                    return null;
                }

                BasicQuery bq = new BasicQuery(qry, startLineNo);
                bq.setQueryParameters(
                        (LinkedHashSet<com.safi.workshop.sqlexplorer.parsers.QueryParameter>) parms);
                return bq;
                // return new BasicQuery(sql.subSequence(start, startOfLine), startLineNo);
            }
            inMLComment = true;
            continue;
        }

        // Only update the startLineNo when we know when code starts
        if (startLineNo < 0 && !Character.isWhitespace(c))
            startLineNo = lineNo;
    }

    // Returns something if there is something to return
    if (start < charIndex) {
        if (rangeIs(startOfLine, charIndex, altSeparator)) {
            charIndex = sql.length();
            if (startLineNo < 0 || start + altSeparator.length() >= startOfLine)
                return null;

            CharSequence qry = sql.subSequence(start, startOfLine);
            Set<com.safi.workshop.sqlexplorer.parsers.QueryParameter> parms = null;
            try {
                parms = parseArgs(qry.toString());
            } catch (ParserException e) {
                e.printStackTrace();
                MessageDialog.openError(SafiWorkshopEditorUtil.getActiveShell(), "Parse Param Error",
                        "Error caught while parsing parameters: " + e.getLocalizedMessage());
                return null;
            }

            BasicQuery bq = new BasicQuery(qry, startLineNo);
            bq.setQueryParameters((LinkedHashSet<com.safi.workshop.sqlexplorer.parsers.QueryParameter>) parms);
            return bq;
            // return new BasicQuery(sql.subSequence(start, startOfLine), startLineNo);
        }

        CharSequence qry = sql.subSequence(start, charIndex);
        Set<com.safi.workshop.sqlexplorer.parsers.QueryParameter> parms = null;
        try {
            parms = parseArgs(qry.toString());
        } catch (ParserException e) {
            e.printStackTrace();
            MessageDialog.openError(SafiWorkshopEditorUtil.getActiveShell(), "Parse Param Error",
                    "Error caught while parsing parameters: " + e.getLocalizedMessage());
            return null;
        }

        BasicQuery bq = new BasicQuery(qry, startLineNo);
        bq.setQueryParameters((LinkedHashSet<com.safi.workshop.sqlexplorer.parsers.QueryParameter>) parms);
        return bq;

        // return new BasicQuery(sql.subSequence(start, charIndex), startLineNo);
    }
    return null;
}

From source file:com.burkeware.search.api.util.StringUtil.java

/**
 * Performs the logic for the <code>split</code> and
 * <code>splitPreserveAllTokens</code> methods that return a maximum array
 * length./*  w ww . j  a v a  2  s  .c  o m*/
 *
 * @param str               the String to parse, may be <code>null</code>
 * @param separatorChars    the separate character
 * @param max               the maximum number of elements to include in the array. A zero or negative value
 *                          implies no limit.
 * @param preserveAllTokens if <code>true</code>, adjacent separators are treated as empty token separators;
 *                          if <code>false</code>, adjacent separators are treated as one separator.
 * @return an array of parsed Strings, <code>null</code> if null String input
 */
private static String[] splitWorker(final String str, final String separatorChars, final int max,
        final boolean preserveAllTokens) {
    if (str == null)
        return null;

    int len = str.length();
    if (len == 0)
        return EMPTY_STRING_ARRAY;

    List<String> list = new ArrayList<String>();
    int sizePlus1 = 1;
    int i = 0, start = 0;
    boolean match = false;
    boolean lastMatch = false;
    if (separatorChars == null) {
        // Null separator means use whitespace
        while (i < len) {
            if (Character.isWhitespace(str.charAt(i))) {
                if (match || preserveAllTokens) {
                    lastMatch = true;
                    if (sizePlus1++ == max) {
                        i = len;
                        lastMatch = false;
                    }
                    list.add(str.substring(start, i));
                    match = false;
                }
                start = ++i;
                continue;
            }
            lastMatch = false;
            match = true;
            i++;
        }
    } else if (separatorChars.length() == 1) {
        // Optimise 1 character case
        char sep = separatorChars.charAt(0);
        while (i < len) {
            if (str.charAt(i) == sep) {
                if (match || preserveAllTokens) {
                    lastMatch = true;
                    if (sizePlus1++ == max) {
                        i = len;
                        lastMatch = false;
                    }
                    list.add(str.substring(start, i));
                    match = false;
                }
                start = ++i;
                continue;
            }
            lastMatch = false;
            match = true;
            i++;
        }
    } else {
        // standard case
        while (i < len) {
            if (separatorChars.indexOf(str.charAt(i)) >= 0) {
                if (match || preserveAllTokens) {
                    lastMatch = true;
                    if (sizePlus1++ == max) {
                        i = len;
                        lastMatch = false;
                    }
                    list.add(str.substring(start, i));
                    match = false;
                }
                start = ++i;
                continue;
            }
            lastMatch = false;
            match = true;
            i++;
        }
    }
    if (match || (preserveAllTokens && lastMatch))
        list.add(str.substring(start, i));

    return list.toArray(new String[list.size()]);
}

From source file:net.sf.jabref.bst.BibtexCaseChanger.java

private int convertCharIfBraceLevelIsZero(char[] c, int start, StringBuilder sb, FORMAT_MODE format) {
    int i = start;
    switch (format) {
    case TITLE_LOWERS:
        if ((i == 0) || (prevColon && Character.isWhitespace(c[i - 1]))) {
            sb.append(c[i]);/* w w w.  j a v a  2s .  c o  m*/
        } else {
            sb.append(Character.toLowerCase(c[i]));
        }
        if (c[i] == ':') {
            prevColon = true;
        } else if (!Character.isWhitespace(c[i])) {
            prevColon = false;
        }
        break;
    case ALL_LOWERS:
        sb.append(Character.toLowerCase(c[i]));
        break;
    case ALL_UPPERS:
        sb.append(Character.toUpperCase(c[i]));
        break;
    default:
        LOGGER.info("convertCharIfBraceLevelIsZero - Unknown format: " + format);
        break;
    }
    i++;
    return i;
}

From source file:de.micromata.genome.gwiki.page.impl.wiki.parser.GWikiWikiParserContext.java

public void flushText() {
    if (collectedText.length() == 0) {
        return;/*  w w w.j a  v  a  2  s  .c om*/
    }
    String t = collectedText.toString();
    collectedText.setLength(0);
    GWikiFragment lf = lastFrag();

    if (t.length() > 0 && Character.isWhitespace(t.charAt(0)) == false) {
        if (lf instanceof GWikiFragmentTextDeco) {
            ((GWikiFragmentTextDeco) lf).setRequireMacroSyntax(true);
        }
    }
    if (ignoreWsNl == true) {
        String s = StringUtils.trim(t);
        if (StringUtils.isBlank(s) || StringUtils.isNewLine(s)) {
            return;
        }
    }
    // int cp = Character.codePointAt(t.toCharArray(), 0);
    if (t.startsWith("<!--") == true) {
        return;
    }
    if (StringUtils.isNewLine(t) == false) {
        addTextFragement(escapeText(t));
    }
}

From source file:com.reprezen.swagedit.assist.SwaggerContentAssistProcessor.java

@Override
protected String extractPrefix(ITextViewer viewer, int offset) {
    int i = offset;
    IDocument document = viewer.getDocument();
    if (i > document.getLength())
        return ""; //$NON-NLS-1$

    try {// w  ww.  ja v a 2  s.  c  o m
        while (i > 0) {
            char ch = document.getChar(i - 1);
            if (Character.isWhitespace(ch))
                break;
            i--;
        }

        return document.get(i, offset - i);
    } catch (BadLocationException e) {
        return ""; //$NON-NLS-1$
    }
}

From source file:com.perl5.lang.perl.lexer.RegexBlock.java

/**
 * Tokenizing regexp object with nested comments and spaces
 * fixme dry it a bit// ww w  .  j  a v a  2 s . c o  m
 *
 * @return array of CustomTokens
 */
protected Collection<CustomToken> tokenizeExtended(PerlStringLexer stringLexer, boolean isSecondBlock) {
    ArrayList<CustomToken> tokens = new ArrayList<CustomToken>();

    int currentOffset = startOffset;
    int blockStart = currentOffset;
    boolean isEscaped = false;
    boolean isCharGroup = false;
    int regexEndOffset = endOffset - 1; // one for quote

    while (currentOffset < regexEndOffset) {
        char currentChar = buffer.charAt(currentOffset);
        int charsLeft = regexEndOffset - currentOffset;

        if (!isEscaped && !isCharGroup && charsLeft > 3
                && "(?#".equals(buffer.subSequence(currentOffset, currentOffset + 3).toString())) {
            if (currentOffset > blockStart) {
                stringLexer.reset(buffer, blockStart, currentOffset, 0);
                tokens.addAll(PerlLexer.processLexer(stringLexer));
            }

            int commentStart = currentOffset;
            currentOffset += 2;
            while (currentOffset < regexEndOffset && buffer.charAt(currentOffset) != ')') {
                currentOffset++;
            }
            if (currentOffset < regexEndOffset) {
                currentOffset++;
            }
            tokens.add(new CustomToken(commentStart, currentOffset, COMMENT_LINE));
            blockStart = currentOffset;
        } else if (!isEscaped && Character.isWhitespace(currentChar)) // whitespace here
        {
            if (currentOffset > blockStart) {
                stringLexer.reset(buffer, blockStart, currentOffset, 0);
                tokens.addAll(PerlLexer.processLexer(stringLexer));
            }

            int whiteSpaceStart = currentOffset;
            while (currentOffset < regexEndOffset && Character.isWhitespace(buffer.charAt(currentOffset))) {
                currentOffset++;
            }
            tokens.add(new CustomToken(whiteSpaceStart, currentOffset, TokenType.WHITE_SPACE));
            blockStart = currentOffset;
        } else if (!isEscaped && currentChar == '#') // comment here
        {
            if (currentOffset > blockStart) {
                stringLexer.reset(buffer, blockStart, currentOffset, 0);
                tokens.addAll(PerlLexer.processLexer(stringLexer));
            }

            int commentStart = currentOffset;
            while (currentOffset < regexEndOffset && buffer.charAt(currentOffset) != '\n') {
                currentOffset++;
            }
            tokens.add(new CustomToken(commentStart, currentOffset, COMMENT_LINE));
            blockStart = currentOffset;
        } else {
            currentOffset++;
        }

        if (!isSecondBlock) {
            if (!isEscaped && !isCharGroup && currentChar == '[') {
                isCharGroup = true;
            } else if (!isEscaped && isCharGroup && currentChar == ']') {
                isCharGroup = false;
            }
        }

        isEscaped = !isEscaped && currentChar == '\\';
    }

    if (currentOffset > blockStart) {
        stringLexer.reset(buffer, blockStart, currentOffset, 0);
        tokens.addAll(PerlLexer.processLexer(stringLexer));
    }

    tokens.add(new CustomToken(currentOffset, currentOffset + 1, REGEX_QUOTE_CLOSE));

    return tokens;
}