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.l2jfree.gameserver.util.Util.java

/**
 * Capitalizes the first letter of every "word" in a string.<BR>
 * (Based on ucwords() function of PHP)/*www .ja  v  a  2 s . c om*/
 * 
 * @param String str
 * @return String containing the modified string.
 */
public static String capitalizeWords(String str) {
    char[] charArray = str.toCharArray();
    String result = "";

    // Capitalize the first letter in the given string!
    charArray[0] = Character.toUpperCase(charArray[0]);

    for (int i = 0; i < charArray.length; i++) {
        if (Character.isWhitespace(charArray[i]))
            charArray[i + 1] = Character.toUpperCase(charArray[i + 1]);

        result += Character.toString(charArray[i]);
    }

    return result;
}

From source file:com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheckTest.java

private static int getLineStart(String line, final int tabWidth) {
    for (int index = 0; index < line.length(); ++index) {
        if (!Character.isWhitespace(line.charAt(index))) {
            return CommonUtils.lengthExpandedTabs(line, index, tabWidth);
        }//from  w  ww .ja  va2s  . c  o m
    }
    return 0;
}

From source file:HardcopyWriter.java

/**
 * This is the write() method of the stream. All Writer subclasses implement
 * this. All other versions of write() are variants of this one
 *//*w  w w .  j a v a 2 s.  com*/
public void write(char[] buffer, int index, int len) {
    synchronized (this.lock) { // For thread safety
        // Loop through all the characters passed to us
        for (int i = index; i < index + len; i++) {
            // If we haven't begun a page (or a new page), do that now.
            if (page == null)
                newpage();

            // If the character is a line terminator, then begin new line,
            // unless it is a \n immediately after a \r.
            if (buffer[i] == '\n') {
                if (!last_char_was_return)
                    newline();
                continue;
            }
            if (buffer[i] == '\r') {
                newline();
                last_char_was_return = true;
                continue;
            } else
                last_char_was_return = false;

            // If it some other non-printing character, ignore it.
            if (Character.isWhitespace(buffer[i]) && !Character.isSpaceChar(buffer[i]) && (buffer[i] != '\t'))
                continue;

            // If no more characters will fit on the line, start new line.
            if (charnum >= chars_per_line) {
                newline();
                // Also start a new page, if necessary
                if (page == null)
                    newpage();
            }

            // Now print the character:
            // If it is a space, skip one space, without output.
            // If it is a tab, skip the necessary number of spaces.
            // Otherwise, print the character.
            // It is inefficient to draw only one character at a time, but
            // because our FontMetrics don't match up exactly to what the
            // printer uses we need to position each character individually
            if (Character.isSpaceChar(buffer[i]))
                charnum++;
            else if (buffer[i] == '\t')
                charnum += 8 - (charnum % 8);
            else {
                page.drawChars(buffer, i, 1, x0 + charnum * charwidth,
                        y0 + (linenum * lineheight) + lineascent);
                charnum++;
            }
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.CodeStyleTest.java

/**
 * Checks the method first line, it should not be empty.
 */// w  w  w  .jav a  2  s  . c o m
private void methodFirstLine(final List<String> lines, final String relativePath) {
    for (int index = 0; index < lines.size() - 1; index++) {
        final String line = lines.get(index);
        if (StringUtils.isBlank(lines.get(index + 1)) && line.length() > 4 && index > 0
                && lines.get(index - 1).startsWith("    ") && Character.isWhitespace(line.charAt(0))
                && line.endsWith("{") && !line.contains(" class ") && !line.contains(" interface ")
                && !line.contains(" @interface ")
                && (!Character.isWhitespace(line.charAt(4)) || line.trim().startsWith("public")
                        || line.trim().startsWith("protected") || line.trim().startsWith("private"))) {
            addFailure("Empty line in " + relativePath + ", line: " + (index + 2));
        }
    }
}

From source file:com.forerunnergames.tools.common.Strings.java

/**
 * Checks whether the string s is comprised of only whitespace. <br/>
 * <br/>// ww w  .j  a v a2s  .c o  m
 * Note: The input string may contain supplementary characters. For rules on which characters are considered
 * whitespace, see @see Character#isWhitespace(char)
 *
 * @param s
 *          The string to check, must not be null.
 *
 * @return True if the string s is comprised of only whitespace or is empty.
 */
public static boolean isWhitespace(final String s) {
    Arguments.checkIsNotNull(s, "s");

    for (int i = 0; i < s.length(); ++i) {
        if (!Character.isWhitespace(s.codePointAt(i)))
            return false;
    }

    return true;
}

From source file:com.jkoolcloud.tnt4j.logger.AppenderTools.java

/**
 * Parse a given message into a map of key/value pairs. Tags are identified by '#key=value .. #keyN=value'
 * sequence. String values should be enclosed in single quotes.
 *
 * @param tags// www. j a va 2 s.co m
 *            a set of name/value pairs
 * @param msg
 *            string message to be parsed
 * @param delm
 *            tag eye catcher
 * @return a map of parsed name/value pairs from a given string message.
 */
public static Map<String, String> parseEventMessage(Map<String, String> tags, String msg, char delm) {
    int curPos = 0;
    while (curPos < msg.length()) {
        if (msg.charAt(curPos) != delm) {
            curPos++;
            continue;
        }

        int start = ++curPos;
        boolean inValue = false;
        boolean quotedValue = false;
        while (curPos < msg.length()) {
            char c = msg.charAt(curPos);
            if (c == '=') {
                inValue = true;
            } else if (c == '\'' && inValue) {
                // the double quote we just read was not escaped, so include it in value
                if (quotedValue) {
                    // found closing quote
                    curPos++;
                    break;
                } else {
                    quotedValue = true;
                }
            } else if (Character.isWhitespace(c) && !quotedValue) {
                break;
            }
            curPos++;
        }

        if (curPos > start) {
            String[] curTag = msg.substring(start, curPos).split("=");
            String name = curTag[0].trim().replace("'", "");
            String value = (curTag.length > 1 ? curTag[1] : "");
            if (value.startsWith("'") && value.endsWith("'"))
                value = StringEscapeUtils.unescapeJava(value.substring(1, value.length() - 1));
            tags.put(name, value);
        }
    }
    return tags;
}

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

/**
 *
 * @param toMeasure/*from  ww w .j a  v  a2 s  . co m*/
 * @param warn
 *            may-be-null
 * @return
 */
public static int width(String toMeasure) {

    /*
     * From Bibtex: We use the natural width for all but special characters,
     * and we complain if the string isn't brace-balanced.
     */

    int i = 0;
    int n = toMeasure.length();
    int braceLevel = 0;
    char[] c = toMeasure.toCharArray();
    int result = 0;

    /*
     * From Bibtex:
     *
     * We use the natural widths of all characters except that some
     * characters have no width: braces, control sequences (except for the
     * usual 13 accented and foreign characters, whose widths are given in
     * the next module), and |white_space| following control sequences (even
     * a null control sequence).
     *
     */
    while (i < n) {
        if (c[i] == '{') {
            braceLevel++;
            if ((braceLevel == 1) && ((i + 1) < n) && (c[i + 1] == '\\')) {
                i++; // skip brace
                while ((i < n) && (braceLevel > 0)) {
                    i++; // skip backslash

                    int afterBackslash = i;
                    while ((i < n) && Character.isLetter(c[i])) {
                        i++;
                    }
                    if ((i < n) && (i == afterBackslash)) {
                        i++; // Skip non-alpha control seq
                    } else {
                        if (BibtexCaseChanger.findSpecialChar(c, afterBackslash).isPresent()) {
                            result += BibtexWidth.getSpecialCharWidth(c, afterBackslash);
                        }
                    }
                    while ((i < n) && Character.isWhitespace(c[i])) {
                        i++;
                    }
                    while ((i < n) && (braceLevel > 0) && (c[i] != '\\')) {
                        if (c[i] == '}') {
                            braceLevel--;
                        } else if (c[i] == '{') {
                            braceLevel++;
                        } else {
                            result += BibtexWidth.getCharWidth(c[i]);
                        }
                        i++;
                    }
                }
                continue;
            }
        } else if (c[i] == '}') {
            if (braceLevel > 0) {
                braceLevel--;
            } else {
                LOGGER.warn("Too many closing braces in string: " + toMeasure);
            }
        }
        result += BibtexWidth.getCharWidth(c[i]);
        i++;
    }
    if (braceLevel > 0) {
        LOGGER.warn("No enough closing braces in string: " + toMeasure);
    }
    return result;
}

From source file:com.tasktop.internal.hp.qc.core.model.comments.mylyn3_8.HtmlStreamTokenizer_m3_8.java

/**
 * parses HTML tag attributes from a buffer and sets them in an HtmlTag_m3_8
 *//* ww w  .j a v  a 2s . c om*/
private static void parseAttributes(HtmlTag_m3_8 tag, String s, int i, boolean escapeValues)
        throws ParseException {
    while (i < s.length()) {
        // skip whitespace
        while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
            i++;
        }

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

        // read the attribute name -- the rule might be looser than the RFC
        // specifies:
        // everything up to a space or an equal sign is included
        int start = i;
        for (; i < s.length() && !Character.isWhitespace(s.charAt(i)) && s.charAt(i) != '='; i++) {
            // just move forward
        }
        String attributeName = s.substring(start, i).toLowerCase(Locale.ENGLISH);

        if (attributeName.equals("/")) { //$NON-NLS-1$
            tag.setSelfTerminating(true);
            continue;
        }

        for (; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) {
            // just move forward
        }
        if (i == s.length() || s.charAt(i) != '=') {
            // no attribute value
            tag.setAttribute(attributeName, ""); //$NON-NLS-1$
            continue;
        }

        // skip whitespace to the start of attribute value
        for (i = i + 1; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) {
            // just move forward
        }
        if (i == s.length()) {
            return;
        }

        // read the attribute value -- the rule for unquoted attribute value
        // is
        // looser than the one in Conolly's W3C 1996 lexical analyzer draft:
        // everything
        // is included up to the next space
        String attributeValue;
        if (s.charAt(i) == '"') {
            start = ++i;
            for (; i < s.length() && s.charAt(i) != '"'; i++) {
                // just move forward
            }
            if (i == s.length()) {
                return; // shouldn't happen if input returned by nextToken
            }
            if (escapeValues) {
                attributeValue = unescape(s.substring(start, i));
            } else {
                attributeValue = s.substring(start, i);
            }
            i++;
        } else if (s.charAt(i) == '\'') {
            start = ++i;
            for (; i < s.length() && s.charAt(i) != '\''; i++) {
                // just move forward
            }
            if (i == s.length()) {
                return; // shouldn't happen if input returned by nextToken
            }
            attributeValue = unescape(s.substring(start, i));
            i++;
        } else {
            start = i;
            for (; i < s.length() && !Character.isWhitespace(s.charAt(i)); i++) {
                // just move forward
            }
            attributeValue = s.substring(start, i);
        }
        tag.setAttribute(attributeName, attributeValue);
    }
}

From source file:gate.creole.splitter.RegexSentenceSplitter.java

@Override
public void execute() throws ExecutionException {
    interrupted = false;//from www  .  jav a  2 s  . c om
    int lastProgress = 0;
    fireProgressChanged(lastProgress);
    //get pointers to the annotation sets
    AnnotationSet outputAS = (outputASName == null || outputASName.trim().length() == 0)
            ? document.getAnnotations()
            : document.getAnnotations(outputASName);

    String docText = document.getContent().toString();

    /* If the document's content is empty or contains only whitespace,
     * we drop out right here, since there's nothing to sentence-split.     */
    if (docText.trim().length() < 1) {
        return;
    }

    Matcher internalSplitMatcher = internalSplitsPattern.matcher(docText);
    Matcher externalSplitMatcher = externalSplitsPattern.matcher(docText);

    Matcher nonSplitMatcher = nonSplitsPattern.matcher(docText);
    //store all non split locations in a list of pairs
    List<int[]> nonSplits = new LinkedList<int[]>();
    while (nonSplitMatcher.find()) {
        nonSplits.add(new int[] { nonSplitMatcher.start(), nonSplitMatcher.end() });
    }
    //this lists holds the next matches at each step
    List<MatchResult> nextSplitMatches = new ArrayList<MatchResult>();
    //initialise matching process
    MatchResult internalMatchResult = null;
    if (internalSplitMatcher.find()) {
        internalMatchResult = internalSplitMatcher.toMatchResult();
        nextSplitMatches.add(internalMatchResult);
    }
    MatchResult externalMatchResult = null;
    if (externalSplitMatcher.find()) {
        externalMatchResult = externalSplitMatcher.toMatchResult();
        nextSplitMatches.add(externalMatchResult);
    }
    MatchResultComparator comparator = new MatchResultComparator();
    int lastSentenceEnd = 0;

    while (!nextSplitMatches.isEmpty()) {
        //see which one matches first
        Collections.sort(nextSplitMatches, comparator);
        MatchResult nextMatch = nextSplitMatches.remove(0);
        if (nextMatch == internalMatchResult) {
            //we have a new internal split; see if it's vetoed or not
            if (!veto(nextMatch, nonSplits)) {
                //split is not vetoed
                try {
                    //add the split annotation
                    FeatureMap features = Factory.newFeatureMap();
                    features.put("kind", "internal");
                    outputAS.add(new Long(nextMatch.start()), new Long(nextMatch.end()), "Split", features);
                    //generate the sentence annotation
                    int endOffset = nextMatch.end();
                    //find the first non whitespace character starting from where the
                    //last sentence ended
                    while (lastSentenceEnd < endOffset
                            && Character.isWhitespace(Character.codePointAt(docText, lastSentenceEnd))) {
                        lastSentenceEnd++;
                    }
                    //if there is any useful text between the two offsets, generate
                    //a new sentence
                    if (lastSentenceEnd < nextMatch.start()) {
                        outputAS.add(new Long(lastSentenceEnd), new Long(endOffset),
                                ANNIEConstants.SENTENCE_ANNOTATION_TYPE, Factory.newFeatureMap());
                    }
                    //store the new sentence end
                    lastSentenceEnd = endOffset;
                } catch (InvalidOffsetException e) {
                    // this should never happen
                    throw new ExecutionException(e);
                }
            }
            //prepare for next step
            if (internalSplitMatcher.find()) {
                internalMatchResult = internalSplitMatcher.toMatchResult();
                nextSplitMatches.add(internalMatchResult);
            } else {
                internalMatchResult = null;
            }
        } else if (nextMatch == externalMatchResult) {
            //we have a new external split; see if it's vetoed or not
            if (!veto(nextMatch, nonSplits)) {
                //split is not vetoed
                try {
                    //generate the split
                    FeatureMap features = Factory.newFeatureMap();
                    features.put("kind", "external");
                    outputAS.add(new Long(nextMatch.start()), new Long(nextMatch.end()), "Split", features);
                    //generate the sentence annotation
                    //find the last non whitespace character, going backward from
                    //where the external skip starts
                    int endOffset = nextMatch.start();
                    while (endOffset > lastSentenceEnd
                            && Character.isSpaceChar(Character.codePointAt(docText, endOffset - 1))) {
                        endOffset--;
                    }
                    //find the first non whitespace character starting from where the
                    //last sentence ended
                    while (lastSentenceEnd < endOffset
                            && Character.isSpaceChar(Character.codePointAt(docText, lastSentenceEnd))) {
                        lastSentenceEnd++;
                    }
                    //if there is any useful text between the two offsets, generate
                    //a new sentence
                    if (lastSentenceEnd < endOffset) {
                        outputAS.add(new Long(lastSentenceEnd), new Long(endOffset),
                                ANNIEConstants.SENTENCE_ANNOTATION_TYPE, Factory.newFeatureMap());
                    }
                    //store the new sentence end
                    lastSentenceEnd = nextMatch.end();
                } catch (InvalidOffsetException e) {
                    // this should never happen
                    throw new ExecutionException(e);
                }
            }
            //prepare for next step
            if (externalSplitMatcher.find()) {
                externalMatchResult = externalSplitMatcher.toMatchResult();
                nextSplitMatches.add(externalMatchResult);
            } else {
                externalMatchResult = null;
            }
        } else {
            //malfunction
            throw new ExecutionException("Invalid state - cannot identify match!");
        }
        //report progress
        int newProgress = 100 * lastSentenceEnd / docText.length();
        if (newProgress - lastProgress > 20) {
            lastProgress = newProgress;
            fireProgressChanged(lastProgress);
        }
    } //while(!nextMatches.isEmpty()){
    fireProcessFinished();
}

From source file:org.crazydog.util.spring.StringUtils.java

/**
 * Trim <i>all</i> whitespace from the given {@code String}:
 * leading, trailing, and in between characters.
 * @param str the {@code String} to check
 * @return the trimmed {@code String}//from  w  w  w  .  jav  a  2 s.  c  o  m
 * @see Character#isWhitespace
 */
public static String trimAllWhitespace(String str) {
    if (!hasLength(str)) {
        return str;
    }
    int len = str.length();
    StringBuilder sb = new StringBuilder(str.length());
    for (int i = 0; i < len; i++) {
        char c = str.charAt(i);
        if (!Character.isWhitespace(c)) {
            sb.append(c);
        }
    }
    return sb.toString();
}