Example usage for java.lang Character isSpaceChar

List of usage examples for java.lang Character isSpaceChar

Introduction

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

Prototype

public static boolean isSpaceChar(int codePoint) 

Source Link

Document

Determines if the specified character (Unicode code point) is a Unicode space character.

Usage

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
 *//*from   w w  w .j  a v  a  2s. c o  m*/
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:util.misc.TextLineBreakerStringWidth.java

/**
 * Read the Next Line in TextReader//from ww  w.ja v  a 2s  .co m
 * @param textReader get next Line from this Reader
 * @param maxWidth Max width of each Line
 * @return one Line
 * @throws IOException
 */
private String readNextLine(Reader textReader, int maxWidth) throws IOException {
    // Clear the current line
    mCurrLineBuffer.setLength(0);

    int lineWidth = 0;
    while (true) {
        // Check whether there is a word that has to be processed first
        if (mNextWordWidth == -1) {
            // There is no unprocessed word any more -> Read to the next word
            // (A length of -1 means it was processed)

            // Ignore white space
            do {
                mCurrChar = textReader.read();

                // Check whether we have to force a line break
                if (isEndOfLine(mCurrChar)) {
                    // Force line break
                    return mCurrLineBuffer.toString();
                }
            } while (Character.isSpaceChar(((char) mCurrChar)));

            // Read the next word
            mNextWord = readNextWord(textReader);
            mNextWordWidth = getStringWidth(mNextWord);
        }

        int newLineWidth = lineWidth + mNextWordWidth;
        if (lineWidth != 0) {
            newLineWidth += mSpaceWidth;
        }

        int lineLength = mCurrLineBuffer.length();
        if (newLineWidth - mSpaceWidth > maxWidth) {
            // The next word does not fit
            if (lineWidth == 0 || (maxWidth - lineWidth > 20)) {
                // The line is empty -> Break the word
                int breakPos = findBreakPos(mNextWord, maxWidth - lineWidth, lineWidth == 0);

                if (breakPos <= 0) {
                    if (mCurrLineBuffer.length() > 0) { // avoid returning empty lines, leading to endless loops
                        return mCurrLineBuffer.toString();
                    } else {
                        breakPos = Math.min(2, mNextWordWidth);
                    }
                }
                String firstPart = mNextWord.substring(0, breakPos);
                if (lineLength > 0 && (mCurrLineBuffer.charAt(lineLength - 1) != '-'
                        || (lineLength > 1 && mCurrLineBuffer.charAt(lineLength - 2) == ' '))) {
                    mCurrLineBuffer.append(' ');
                }
                mCurrLineBuffer.append(firstPart);

                // Append a minus if the last character is a letter or digit
                char lastChar = firstPart.charAt(firstPart.length() - 1);
                if (Character.isLetterOrDigit(lastChar)) {
                    mCurrLineBuffer.append('-');
                }

                mNextWord = mNextWord.substring(breakPos);
                mNextWordWidth = getStringWidth(mNextWord);

                return mCurrLineBuffer.toString();
            } else {
                // Make a line break here (and process the word the next time)
                return mCurrLineBuffer.toString();
            }
        } else {
            if (lineWidth != 0) {
                // Add a space, but not if our current word ends with "-"
                char lastChar = mCurrLineBuffer.charAt(lineLength - 1);
                if (lastChar != '/' && (lastChar != '-'
                        || (lineLength >= 2 && mCurrLineBuffer.charAt(lineLength - 2) == ' '))) {
                    mCurrLineBuffer.append(' ');
                }
                lineWidth += mSpaceWidth;
            }

            // The next word fits -> Add it
            mCurrLineBuffer.append(mNextWord);
            lineWidth += mNextWordWidth;
            mNextWordWidth = -1; // Mark the word as processed

            // Check whether we have to force a line break
            if (isEndOfLine(mCurrChar)) {
                // Force line break
                return mCurrLineBuffer.toString();
            }
        }
    }
}

From source file:com.mgmtp.jfunk.data.generator.util.GeneratingExpression.java

/**
 * Replaces randomly selected characters in the given string with forbidden characters according
 * to the given expression.//w  w  w  .j av a2  s.  co  m
 * 
 * @param bad
 *            if bad = -2 all characters are replaced, if bad = -1 1 - (all - 1) are replaced,
 *            if bad > 0 the exact number of characters is replaced
 * @param input
 *            the input string
 * @return input with <code>bad</code> replaced characters
 */
public String negateString(final String input, int bad) {
    int length = input.length();
    Range[] ranges = getRanges();
    int[] lengths = new int[ranges.length];
    // arrange lengths
    for (int i = 0; i < lengths.length; i++) {
        Range r = ranges[i];
        lengths[i] = r.getMin();
        length -= r.getMin();
    }
    /**
     * distribute remaining lengths
     */
    int i = 0;
    // only 1000 tries otherwise break as it just does not work
    while (length > 0 && i < 1000) {
        int index = i % lengths.length;
        Range r = ranges[index];
        if (lengths[index] < r.getMax()) {
            lengths[index] += 1;
            length--;
        }
        i++;
    }

    // generate completely negative string
    String replaceString = generate(lengths, -2);
    if (replaceString.length() == 0) {
        log.warn("No negative characters possible in this expression. All characters are allowed.");
        return input;
    }
    // now replace the #bad character in the input string
    List<Integer> l = new ArrayList<Integer>(input.length());
    for (i = 0; i < input.length(); i++) {
        l.add(i);
    }
    if (bad == -2) {
        // all false
        bad = input.length();
    } else if (bad == -1) {
        bad = 1 + random.getInt(input.length() - 1);
    }
    Collections.shuffle(l);
    StringBuffer base = new StringBuffer(input);
    int j = 0;
    for (i = 0; i < bad; i++) {
        int index = l.remove(0);
        char replaceChar = ' ';
        if (index < replaceString.length()) {
            replaceChar = replaceString.charAt(index);
        }
        while ((index == 0 || index >= replaceString.length() || index == input.length() - 1)
                && Character.isSpaceChar(replaceChar)) {
            replaceChar = replaceString.charAt(j);
            j = (j + 1) % replaceString.length();
        }
        base.setCharAt(index, replaceChar);
    }
    if (log.isDebugEnabled()) {
        log.debug("False characters in string; " + input + " became " + base);
    }
    return base.toString();
}

From source file:org.zaproxy.zap.extension.api.GoAPIGenerator.java

private static String toTitleCase(String input) {
    StringBuilder titleCase = new StringBuilder();
    boolean nextTitleCase = true;
    for (char c : input.toCharArray()) {
        if (Character.isSpaceChar(c)) {
            nextTitleCase = true;// w  w w  . java  2s. c om
        } else if (nextTitleCase) {
            c = Character.toTitleCase(c);
            nextTitleCase = false;
        }
        titleCase.append(c);
    }
    return titleCase.toString();
}

From source file:org.jcryptool.commands.core.evaluator.CommandEvaluator.java

/**
 * Sprits command Arg String into its parts. Needs to parse text cause of " " text grouping. \" escapes " for text
 * usage.//  ww  w.  ja  v a 2s.  c  om
 *
 * @param commandArgs
 * @return
 * @throws ParseException
 */
private String[] splitArgs(String commandArgs) throws ParseException {
    ArrayList<String> args = new ArrayList<String>();
    StringBuilder arg = new StringBuilder();
    boolean stringMode = false;
    boolean escapeMode = false;
    for (int i = 0; i < commandArgs.length(); i++) {
        char actualChar = commandArgs.charAt(i);
        if (Character.isSpaceChar(actualChar)) {
            escapeMode = false;
            if (stringMode) {
                arg.append(actualChar);
            } else {
                args.add(arg.toString());
                arg.delete(0, arg.length());
            }
        } else if (actualChar == '"') {
            if (escapeMode) {
                arg.deleteCharAt(arg.length() - 1);
                arg.append(actualChar);
                escapeMode = false;
            } else {
                stringMode = !stringMode;
            }
        } else if (actualChar == '\\') {
            arg.append(actualChar);
            escapeMode = true;
        } else {
            escapeMode = false;
            arg.append(actualChar);
        }
    }
    if (arg.length() > 0) {
        args.add(arg.toString());
    }

    if (stringMode) {
        throw new ParseException(
                "Illegal use of \". It needs to be escaped with \\\" or used as a pair that encloses text like \"hello world\""); //$NON-NLS-1$
    }

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

From source file:org.wisdom.maven.utils.Properties2HoconConverter.java

private static int getValueStartPosition(String line, int keyIndex) {
    int i = keyIndex;
    for (; i < line.length(); i++) {
        char c = line.charAt(i);
        if (!Character.isSpaceChar(c) && c != '=' && c != ':') {
            return i;
        }/*w  ww.j a  v a2s . c om*/
    }
    return -1;
}

From source file:edu.ku.brc.af.ui.db.JEditComboBox.java

protected KeyAdapter createKeyAdapter() {
    return new KeyAdapter() {
        @Override//from   w w w  .j  a  va 2s.  c  o m
        public void keyReleased(KeyEvent ev) {
            char key = ev.getKeyChar();

            if (ev.getKeyCode() == clearKeyStroke.getKeyCode()) {
                int selectedIndex = getSelectedIndex();
                if (selectedIndex > -1 && dbAdapter != null && textField != null
                        && textField.getText().length() == 0 && !dbAdapter.isReadOnly()) {
                    // delete item
                    PickListItem item = (PickListItem) getSelectedItem();
                    dbAdapter.getList().remove(item);
                }

            } else if (!(Character.isLetterOrDigit(key) || Character.isSpaceChar(key))) {
                if (ev.getKeyCode() == KeyEvent.VK_ENTER) {
                    addNewItemFromTextField();
                }
            } else {
                if (textField != null) {
                    if (getSelectedIndex() > -1) {
                        int pos = textField.getCaretPosition();
                        String currentText = textField.getText();
                        setSelectedIndex(-1);
                        textField.setText(currentText);
                        textField.moveCaretPosition(pos);
                        textField.setSelectionStart(pos);
                        textField.setSelectionEnd(pos);
                    }

                } else {
                    setSelectedIndex(-1);
                }
            }
        }
    };
}

From source file:org.wisdom.maven.utils.Properties2HoconConverter.java

private static int getIndexOf(String line, char c) {
    int begin = 0;
    int i = 0;/*from ww w. ja  v  a2 s . c  o  m*/
    // Skip any space character.
    for (; begin == 0 && i < line.length(); i++) {
        if (!Character.isSpaceChar(line.charAt(i))) {
            begin = i + 1;
        }
    }
    if (i == line.length()) {
        return -1;
    }
    int pos = line.indexOf(c, begin);
    while (pos != -1) {
        if (pos == 0) {
            return 0;
        } else if (line.charAt(pos - 1) == '\\') {
            // Escaped
            pos = line.indexOf(c, pos + 1);
        } else {
            return pos;
        }
    }
    return -1;
}

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

@Override
public void execute() throws ExecutionException {
    interrupted = false;//from   ww  w . j  av a2  s . c o m
    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.ebayopensource.turmeric.tools.errorlibrary.util.ErrorLibraryUtils.java

public static boolean validateVariableSemantics(String argument) {

    //TODO  use regular expression instead to check for both upper and lower case alphabets
    boolean isValidate = true;
    if (argument != null)
        for (int i = 0; i < argument.length(); i++)
            if (Character.isWhitespace(argument.charAt(i)) || Character.isSpaceChar(argument.charAt(i))) {
                isValidate = false;/*from  w  w  w . j a va2  s.  c  o m*/
                break;
            }
    return isValidate;
}