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:com.puppycrawl.tools.checkstyle.checks.whitespace.WhitespaceAroundCheck.java

@Override
public void visitToken(DetailAST ast) {
    final int currentType = ast.getType();
    if (isNotRelevantSituation(ast, currentType)) {
        return;/*from ww w  . j  a v  a  2  s  .c  om*/
    }

    final String line = getLine(ast.getLineNo() - 1);
    final int before = ast.getColumnNo() - 1;
    final int after = ast.getColumnNo() + ast.getText().length();

    if (before >= 0 && !Character.isWhitespace(line.charAt(before))) {
        log(ast.getLineNo(), ast.getColumnNo(), WS_NOT_PRECEDED, ast.getText());
    }

    if (after >= line.length()) {
        return;
    }

    final char nextChar = line.charAt(after);
    if (!Character.isWhitespace(nextChar)
            // Check for "return;"
            && !(currentType == TokenTypes.LITERAL_RETURN && ast.getFirstChild().getType() == TokenTypes.SEMI)
            && !isAnonymousInnerClassEnd(currentType, nextChar)) {

        log(ast.getLineNo(), ast.getColumnNo() + ast.getText().length(), WS_NOT_FOLLOWED, ast.getText());
    }
}

From source file:com.google.dart.tools.ui.internal.text.dart.DartAutoIndentStrategy_NEW.java

/**
 * Indents line <code>line</code> in <code>document</code> with <code>indent</code>. Leaves
 * leading comment signs alone.//from w  ww . j  a v a  2  s  .co m
 * 
 * @param document the document
 * @param line the line
 * @param indent the indentation to insert
 * @param tabLength the length of a tab
 * @throws BadLocationException on concurrent document modification
 */
private void addIndent(Document document, int line, CharSequence indent, int tabLength)
        throws BadLocationException {
    IRegion region = document.getLineInformation(line);
    int insert = region.getOffset();
    int endOffset = region.getOffset() + region.getLength();

    // Compute insert after all leading line comment markers
    int newInsert = insert;
    while (newInsert < endOffset - 2 && document.get(newInsert, 2).equals(LINE_COMMENT)) {
        newInsert += 2;
    }

    // Heuristic to check whether it is commented code or just a comment
    if (newInsert > insert) {
        int whitespaceCount = 0;
        int i = newInsert;
        while (i < endOffset - 1) {
            char ch = document.get(i, 1).charAt(0);
            if (!Character.isWhitespace(ch)) {
                break;
            }
            whitespaceCount = whitespaceCount + computeVisualLength(ch, tabLength);
            i++;
        }

        if (whitespaceCount != 0 && whitespaceCount >= CodeFormatterUtil.getIndentWidth(null)) {
            insert = newInsert;
        }
    }

    // Insert indent
    document.replace(insert, 0, indent.toString());
}

From source file:de.fau.cs.osr.utils.StringUtils.java

/**
 * Collapses a sequence of multiple whitespace characters into a single
 * space. Does NOT trim the string./*from w w  w .j a  va2 s . c  om*/
 */
public static String collapseWhitespace(String trim) {
    if (trim.isEmpty())
        return trim;

    StringBuilder b = new StringBuilder(trim.length());
    for (int i = 0; i < trim.length(); ++i) {
        char ch = trim.charAt(i);
        if (Character.isWhitespace(ch)) {
            b.append(' ');
            int j = i + 1;
            while (j < trim.length() && Character.isWhitespace(trim.charAt(j)))
                ++j;
            i = j - 1;
        } else
            b.append(ch);
    }
    return b.toString();
}

From source file:HexFormat.java

/**
 * Parse a hex number into a Number object. Hexadecimal numbers may be
 * indicated with a leading character designation of '0x'. If up to 1 byte
 * is parsed, returns a Byte. If more than 1 and up to 2 bytes are parsed,
 * return a Short. If more than 2 and up to 4 bytes are parsed, return an
 * Integer. If more than 4 and up to 8 bytes are parsed, return a Long.
 * // www.  ja  v a  2  s .c  o m
 * @param text
 *            a hexadecimal number
 * @param parsePosition
 *            position to start parsing from
 * @return return an integer form of Number object if parse is successful;
 *         <CODE>null</CODE> otherwise
 * 
 * @since 1.0
 */
public Number parse(String text, ParsePosition parsePosition) {
    boolean skipWhitespace = true;
    int startIndex, nibbles;

    // remove whitespace
    StringCharacterIterator iter = new StringCharacterIterator(text, parsePosition.getIndex());
    for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) {
        if (skipWhitespace && Character.isWhitespace(c)) {
            // skip whitespace
            continue;
        }
        break;
    }

    // skip a leading hex designation of the characters '0x'
    if (text.regionMatches(iter.getIndex(), "0x", 0, 2)) {
        parsePosition.setIndex(iter.getIndex() + 2);
    } else {
        parsePosition.setIndex(iter.getIndex());
    }

    startIndex = parsePosition.getIndex();
    Number result = (Number) parseObject(text, parsePosition);

    if (result == null) {
        return (result);
    }

    nibbles = parsePosition.getIndex() - startIndex;
    if (nibbles <= 2) {
        result = new Byte(result.byteValue());
    } else if (nibbles <= 4) {
        result = new Short(result.shortValue());
    } else if (nibbles <= 8) {
        result = new Integer(result.intValue());
    } else if (nibbles <= 16) {
        result = new Long(result.longValue());
    }
    return (result);
}

From source file:com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceAfterCheck.java

/**
 * Checks if current line has redundant whitespace after specified index.
 * @param line line of java source.// w  w  w .  j  av  a  2  s  .com
 * @param after specified index.
 * @return true if line contains redundant whitespace.
 */
private boolean hasRedundantWhitespace(String line, int after) {
    boolean result = !allowLineBreaks;
    for (int i = after + 1; !result && i < line.length(); i++) {
        if (!Character.isWhitespace(line.charAt(i))) {
            result = true;
        }
    }
    return result;
}

From source file:BasicEditor3.java

/**
 * Reads a word from the given text starting from the offset. 
 * @param text//ww w .  jav  a  2 s  .  co m
 * @param offset
 * @return
 */
String readWord(String text, int offset) {
    StringBuffer sb = new StringBuffer();
    int index = offset;
    char c = 0;

    while (index < text.length()) {
        c = text.charAt(index);
        if (Character.isWhitespace(c))
            break;

        sb.append(c);
        index += 1;
    }

    return sb.toString();
}

From source file:net.sf.jabref.gui.AutoCompleteListener.java

@Override
public void keyTyped(KeyEvent e) {
    LOGGER.debug("key typed event caught " + e.getKeyCode());
    char ch = e.getKeyChar();
    if (ch == '\n') {
        // this case is handled at keyPressed(e)
        return;/* w w w.j  a va2 s.co  m*/
    }

    if ((e.getModifiers() | InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
        // plain key or SHIFT + key is pressed, no handling of CTRL+key,  META+key, ...
        if (Character.isLetter(ch) || Character.isDigit(ch)
                || (Character.isWhitespace(ch) && completer.isSingleUnitField())) {
            JTextComponent comp = (JTextComponent) e.getSource();

            if (toSetIn == null) {
                LOGGER.debug("toSetIn is null");
            } else {
                LOGGER.debug("toSetIn: >" + toSetIn + '<');
            }

            // The case-insensitive system is a bit tricky here
            // If keyword is "TODO" and user types "tO", then this is treated as "continue" as the "O" matches the "O"
            // If keyword is "TODO" and user types "To", then this is treated as "discont" as the "o" does NOT match the "O".

            if ((toSetIn != null) && (toSetIn.length() > 1) && (ch == toSetIn.charAt(1))) {
                // User continues on the word that was suggested.
                LOGGER.debug("cont");

                toSetIn = toSetIn.substring(1);
                if (!toSetIn.isEmpty()) {
                    int cp = comp.getCaretPosition();
                    //comp.setCaretPosition(cp+1-toSetIn.);
                    //System.out.println(cp-toSetIn.length()+" - "+cp);
                    comp.select((cp + 1) - toSetIn.length(), cp);
                    lastBeginning = lastBeginning + ch;

                    e.consume();
                    lastCaretPosition = comp.getCaretPosition();

                    //System.out.println("Added char: '"+toSetIn+"'");
                    //System.out.println("LastBeginning: '"+lastBeginning+"'");

                    lastCompletions = findCompletions(lastBeginning, comp);
                    lastShownCompletion = 0;
                    for (int i = 0; i < lastCompletions.length; i++) {
                        String lastCompletion = lastCompletions[i];
                        //System.out.println("Completion["+i+"] = "+lastCompletion);
                        if (lastCompletion.endsWith(toSetIn)) {
                            lastShownCompletion = i;
                            break;
                        }

                    }
                    //System.out.println("Index now: "+lastShownCompletion);
                    if (toSetIn.length() < 2) {
                        // User typed the last character of the autocompleted word
                        // We have to replace the automcompletion word by the typed word.
                        // This helps if the user presses "space" after the completion
                        // "space" indicates that the user does NOT want the autocompletion,
                        // but the typed word
                        String text = comp.getText();
                        comp.setText(text.substring(0, lastCaretPosition - lastBeginning.length())
                                + lastBeginning + text.substring(lastCaretPosition));
                        // there is no selected text, therefore we are not updating the selection
                        toSetIn = null;
                    }
                    return;
                }
            }

            if ((toSetIn != null) && ((toSetIn.length() <= 1) || (ch != toSetIn.charAt(1)))) {
                // User discontinues the word that was suggested.
                lastBeginning = lastBeginning + ch;

                LOGGER.debug("discont toSetIn: >" + toSetIn + "'<' lastBeginning: >" + lastBeginning + '<');

                String[] completed = findCompletions(lastBeginning, comp);
                if ((completed != null) && (completed.length > 0)) {
                    lastShownCompletion = 0;
                    lastCompletions = completed;
                    String sno = completed[0];
                    // toSetIn = string used for autocompletion last time
                    // this string has to be removed
                    // lastCaretPosition is the position of the caret after toSetIn.
                    int lastLen = toSetIn.length() - 1;
                    toSetIn = sno.substring(lastBeginning.length() - 1);
                    String text = comp.getText();
                    //Util.pr(""+lastLen);
                    //we do not use toSetIn as we want to obey the casing of "sno"
                    comp.setText(text.substring(0, (lastCaretPosition - lastLen - lastBeginning.length()) + 1)
                            + sno + text.substring(lastCaretPosition));
                    int startSelect = (lastCaretPosition + 1) - lastLen;
                    int endSelect = (lastCaretPosition + toSetIn.length()) - lastLen;
                    comp.select(startSelect, endSelect);

                    lastCaretPosition = comp.getCaretPosition();
                    e.consume();
                    return;
                } else {
                    setUnmodifiedTypedLetters(comp, true, false);
                    e.consume();
                    toSetIn = null;
                    return;
                }
            }

            LOGGER.debug("case else");

            comp.replaceSelection("");

            StringBuffer currentword = getCurrentWord(comp);
            if (currentword == null) {
                currentword = new StringBuffer();
            }

            // only "real characters" end up here
            assert (!Character.isISOControl(ch));
            currentword.append(ch);
            startCompletion(currentword, e);
            return;
        } else {
            if (Character.isWhitespace(ch)) {
                assert (!completer.isSingleUnitField());
                LOGGER.debug("whitespace && !singleUnitField");
                // start a new search if end-of-field is reached

                // replace displayed letters with typed letters
                setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, true);
                resetAutoCompletion();
                return;
            }

            LOGGER.debug("No letter/digit/whitespace or CHAR_UNDEFINED");
            // replace displayed letters with typed letters 
            setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, !Character.isISOControl(ch));
            resetAutoCompletion();
            return;
        }
    }
    resetAutoCompletion();
}

From source file:br.msf.commons.util.CharSequenceUtils.java

public static boolean isBlankOrNull(final CharSequence sequence) {
    if (isEmptyOrNull(sequence)) {
        return true;
    }//from w  w w.j av  a2 s. c  o m
    int first;
    /* finds the first non-space char index */
    for (first = 0; first < sequence.length(); first++) {
        if (!Character.isWhitespace(sequence.charAt(first))) {
            break;
        }
    }
    return first >= sequence.length();
}

From source file:com.liferay.cucumber.util.StringUtil.java

public static String trim(String s) {
    if (s == null) {
        return null;
    }/* www.  j av  a  2 s.c o  m*/

    if (s.length() == 0) {
        return s;
    }

    int len = s.length();

    int x = len;

    for (int i = 0; i < len; i++) {
        char c = s.charAt(i);

        if (!Character.isWhitespace(c)) {
            x = i;

            break;
        }
    }

    if (x == len) {
        return StringPool.BLANK;
    }

    int y = x + 1;

    for (int i = len - 1; i > x; i--) {
        char c = s.charAt(i);

        if (!Character.isWhitespace(c)) {
            y = i + 1;

            break;
        }
    }

    if ((x == 0) && (y == len)) {
        return s;
    }

    return s.substring(x, y);
}

From source file:PrintTextWrapPagetation.java

void printText() {
    printer.startPage();//from   w w  w. ja v  a2s.  co m
    wordBuffer = new StringBuffer();
    x = leftMargin;
    y = topMargin;
    index = 0;
    end = textToPrint.length();
    while (index < end) {
        char c = textToPrint.charAt(index);
        index++;
        if (c != 0) {
            if (c == 0x0a || c == 0x0d) {
                if (c == 0x0d && index < end && textToPrint.charAt(index) == 0x0a) {
                    index++; // if this is cr-lf, skip the lf
                }
                printWordBuffer();
                newline();
            } else {
                if (c != '\t') {
                    wordBuffer.append(c);
                }
                if (Character.isWhitespace(c)) {
                    printWordBuffer();
                    if (c == '\t') {
                        x += tabWidth;
                    }
                }
            }
        }
    }
    if (y + lineHeight <= bottomMargin) {
        printer.endPage();
    }
}