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:Main.java

/**
 * collapse multi-whitespace into one whitespace in the original text.
 * Support unicode white space with isWhitespace and isSpaceChar method in
 * {@link #Character}//from   w w w .  j  ava  2 s  .  com
 * 
 * @param oriText
 * @return
 */
public static String collapseWhiteSpace(StringBuffer oriText) {
    if (oriText == null) {
        return null;
    }

    int oriLen = oriText.length();
    StringBuffer newText = new StringBuffer(oriLen);
    int wsCount = 0;
    char lastWs = ' ';

    for (int i = 0; i <= oriLen; i++) {
        if (i == oriLen) {
            if (wsCount == 1) {
                newText.append(lastWs);
            }

            if (wsCount > 1) {
                newText.append(' ');
            }

            wsCount = 0;
            break;
        }

        char c = oriText.charAt(i);
        if (Character.isWhitespace(c) || Character.isSpaceChar(c)) {
            wsCount++;
            lastWs = c;
        } else {
            if (wsCount == 1) {
                newText.append(lastWs);
            }

            if (wsCount > 1) {
                newText.append(' ');
            }

            wsCount = 0;

            newText.append(c);
        }
    }

    String relt = newText.toString();
    return relt;
}

From source file:wo.trade.Util.java

public static String removeThoseDamnWhiteSpace(String s) {
    s = StringUtils.deleteWhitespace(s);
    StringBuilder sb = new StringBuilder();
    char[] charArray = s.toCharArray();
    for (char c : charArray) {
        if (!Character.isSpaceChar(c)) {
            sb.append(c);//from w w  w . j  a  va  2 s . co  m
        }
    }
    return sb.toString();
}

From source file:org.talend.repository.json.util.JSONUtil.java

public static boolean validateLabelForJSON(String label) {
    if (label == null) {
        return false;
    }// w  ww.ja  v  a 2 s .c  om
    if (label.length() < 1) {
        return false;
    }
    char firstChar = label.charAt(0);
    // see bug 10359,support begin with "_".
    if (!Character.isLetter(firstChar) && !('_' == firstChar)) {
        return false;
    }
    //        if (label.toLowerCase().startsWith("xml")) { //$NON-NLS-1$
    // return false;
    // }
    char[] array = label.toCharArray();
    for (char element : array) {
        if (Character.isSpaceChar(element) || Character.isWhitespace(element)) {
            return false;
        }
    }
    return true;
}

From source file:com.jaspersoft.studio.server.wizard.pages.UsernameValidator.java

public IStatus validate(Object value) {
    String uname = (String) value;
    if (value == null || uname.isEmpty())
        return ValidationStatus.error(Messages.EmptyStringValidator_EmptyError);
    if (uname.length() > 100)
        return ValidationStatus.error(Messages.UsernameValidator_ErrorMsgUsernameTooLong);
    for (char c : uname.toCharArray()) {
        if (!Character.isSpaceChar(c)) {
            if (!ArrayUtils.contains(NOT_ALLOWED_ID_CHARS, c)) {
                continue;
            } else {
                return ValidationStatus.error(Messages.UsernameValidator_ErrorMsgNotAllowedChars);
            }// w ww. j  a v a 2 s  .  co  m
        } else {
            return ValidationStatus.error(Messages.UsernameValidator_ErrorMsgNoSpaceChars);
        }
    }

    return Status.OK_STATUS;
}

From source file:com.haulmont.cuba.gui.components.autocomplete.impl.HintProvider.java

/**
 * Returns word in query denoting entity or field parameter user have requested hint for
 * @param queryString query string// w w  w.ja  va  2 s. c  om
 * @param caretPosition caret position
 * @return matched word or empty string
 */
public static String getLastWord(String queryString, int caretPosition) {
    if (caretPosition < 0)
        return "";

    if (Character.isSpaceChar(queryString.charAt(caretPosition))) {
        return "";
    }

    String[] words = queryString.substring(0, caretPosition + 1).split("\\s");
    String result = words[words.length - 1];

    if (StringUtils.isBlank(result)) {
        return result;
    }

    int leftBracketsIdx = result.lastIndexOf('(');
    if (leftBracketsIdx >= 0 && leftBracketsIdx < result.length()) {
        result = result.substring(leftBracketsIdx + 1);
    }

    result = getLastWordWithArithmeticOperation(result);

    return result;
}

From source file:Main.java

public void setEditor(ComboBoxEditor anEditor) {
    super.setEditor(anEditor);
    if (anEditor.getEditorComponent() instanceof JTextField) {
        tf = (JTextField) anEditor.getEditorComponent();
        tf.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent ev) {
                char key = ev.getKeyChar();
                if (!(Character.isLetterOrDigit(key) || Character.isSpaceChar(key))) {
                    return;
                }//from   w  w w . j a  va2  s . c  o  m
                String s = tf.getText();
                caretPos = tf.getCaretPosition();
                try {
                    String text = tf.getText(0, caretPos);
                    int n = getItemCount();
                    for (int i = 0; i < n; i++) {
                        int ind = ((String) getItemAt(i)).indexOf(text);
                        if (ind == 0) {
                            setSelectedIndex(i);
                            return;
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}

From source file:org.apache.wookie.w3c.util.UnicodeUtils.java

/**
 * Normalizes all space characters (and whitespace if includeWhitespace is set to true) in the given string to 
 * U+0020, then collapses multiple adjacent spaces to a single space, and
 * removes any leading and trailing spaces. If the input string is null,
 * the method returns an empty string ("")
 * @param in the string to normalize//from ww w .j  a v a  2  s . c  om
 * @param includeWhitespace set to true to normalize whitespace as well as space characters
 * @return the normalized string
 */
private static String normalize(String in, boolean includeWhitespace) {
    if (in == null)
        return "";
    // Create a buffer for the string
    StringBuffer buf = new StringBuffer();
    // Iterate over characters in the string and append them to buffer, replacing matching characters with standard spaces
    for (int x = 0; x < in.length(); x++) {
        char ch = in.charAt(x);
        if (Character.isSpaceChar(ch) || (Character.isWhitespace(ch) && includeWhitespace)) {
            ch = ' ';
        }
        buf.append(ch);
    }
    String str = buf.toString();
    // Squeeze out extra spaces
    str = CharSetUtils.squeeze(str, " ");
    // Strip off trailing and leading spaces
    str = StringUtils.strip(str);
    return str;
}

From source file:org.minig.imap.mime.impl.ParenListParser.java

public int consumeToken(int parsePosition, byte[] s) {
    if (parsePosition >= s.length) {
        return parsePosition;
    }//from w  w  w .ja  v  a  2 s.c  o m
    int cur = parsePosition;
    while (Character.isSpaceChar(charAt(s, cur))) {
        cur++;
    }

    switch (charAt(s, cur)) {
    case 'N':
        lastReadToken = "NIL".getBytes();
        lastTokenType = TokenType.NIL;
        return cur + 3;
    case '"':
        int last = indexOf(s, '"', cur + 1);
        lastReadToken = substring(s, cur + 1, last);
        lastTokenType = TokenType.STRING;
        return last + 1;
    case '(':
        int close = ParenMatcher.closingParenIndex(s, cur);
        lastReadToken = substring(s, cur + 1, close);
        // FIXME
        if (startsWith(lastReadToken, "\"TEXT\"")) {
            lastReadToken = ("(" + new String(lastReadToken) + ")").getBytes();
        }
        lastTokenType = TokenType.LIST;
        return close + 1;
    case '{':
        int size = cur + 1;
        while (charAt(s, size) != '}') {
            size++;
        }
        int bytes = Integer.parseInt(new String(substring(s, cur + 1, size)));
        int atomStart = size + 1;
        // +1 pattern, don't ask
        if (charAt(s, atomStart) == '}') {
            atomStart++;
        }
        byte[] out = new byte[bytes];
        System.arraycopy(s, atomStart, out, 0, bytes);
        lastReadToken = out;
        lastTokenType = TokenType.ATOM;
        return atomStart + bytes;
    default:
        // number
        int digit = cur;
        while (Character.isDigit(charAt(s, digit))) {
            digit++;
        }
        lastReadToken = substring(s, cur, digit);
        lastTokenType = TokenType.DIGIT;
        return digit + 1;
    }
}

From source file:io.mapzone.controller.vm.http.HttpForwarder.java

/**
 * Encodes characters in the query or fragment part of the URI.
 *
 * <p>/* w  w w.  j a v  a 2 s.  c  o  m*/
 * Unfortunately, an incoming URI sometimes has characters disallowed by the
 * spec. HttpClient insists that the outgoing proxied request has a valid URI
 * because it uses Java's {@link URI}. To be more forgiving, we must escape the
 * problematic characters. See the URI class for the spec.
 *
 * @param in example: name=value&foo=bar#fragment
 */
protected static CharSequence encodeUriQuery(CharSequence in) {
    // Note that I can't simply use URI.java to encode because it will escape
    // pre-existing escaped things.
    StringBuilder outBuf = null;
    Formatter formatter = null;
    for (int i = 0; i < in.length(); i++) {
        char c = in.charAt(i);
        boolean escape = true;
        if (c < 128) {
            if (asciiQueryChars.get((int) c)) {
                escape = false;
            }
        } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {// not-ascii
            escape = false;
        }
        if (!escape) {
            if (outBuf != null)
                outBuf.append(c);
        } else {
            // escape
            if (outBuf == null) {
                outBuf = new StringBuilder(in.length() + 5 * 3);
                outBuf.append(in, 0, i);
                formatter = new Formatter(outBuf);
            }
            // leading %, 0 padded, width 2, capital hex
            formatter.format("%%%02X", (int) c);// TODO
        }
    }
    return outBuf != null ? outBuf : in;
}

From source file:net.jforum.util.URLNormalizer.java

  /**
 * /*from  w  w w .ja  va 2  s  .  c o  m*/
 * @param url the url to normalize
 * @param limit do not process more than <code>limit + 1</code> chars
 * @param friendlyTruncate If <code>true</code>, will try to not cut a word if
 * more than <code>limit</code> chars were processed. It will stop in the next
 * special char
 * @return the normalized url
 */
public static String normalize(String url, int limit, boolean friendlyTruncate)
{
  char[] chars = url.toCharArray();
    
  StringBuffer sb = new StringBuffer(url.length());
    
  for (int i = 0; i < chars.length; i++) {
    if (i <= limit || (friendlyTruncate && i > limit && sb.charAt(sb.length() - 1) != '_')) {
        
      if (Character.isSpaceChar(chars[i]) || chars[i] == '-') {
        if (friendlyTruncate && i > limit) {
          break;
        }
          
        if (i > 0 && sb.charAt(sb.length() - 1) != '_') {
          sb.append('_');
        }
      }
        
      if (Character.isLetterOrDigit(chars[i])) {
        sb.append(chars[i]);
      }
      else if (friendlyTruncate && i > limit) {
        break;
      }
    }
  }
    
  return sb.toString().toLowerCase();
}