Example usage for java.lang Character charCount

List of usage examples for java.lang Character charCount

Introduction

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

Prototype

public static int charCount(int codePoint) 

Source Link

Document

Determines the number of char values needed to represent the specified character (Unicode code point).

Usage

From source file:Main.java

/**
 * Find the start of the next token.  A token is composed of letters and numbers. Any other
 * character are considered delimiters.//from  w  w  w .  j  a  v a2  s.  c  o m
 *
 * @param line The string to search for the next token.
 * @param startIndex The index to start searching.  0 based indexing.
 * @return The index for the start of the next token.  line.length() if next token not found.
 */
@VisibleForTesting
static int findNextTokenStart(String line, int startIndex) {
    int index = startIndex;

    // If already in token, eat remainder of token.
    while (index <= line.length()) {
        if (index == line.length()) {
            // No more tokens.
            return index;
        }
        final int codePoint = line.codePointAt(index);
        if (!Character.isLetterOrDigit(codePoint)) {
            break;
        }
        index += Character.charCount(codePoint);
    }

    // Out of token, eat all consecutive delimiters.
    while (index <= line.length()) {
        if (index == line.length()) {
            return index;
        }
        final int codePoint = line.codePointAt(index);
        if (Character.isLetterOrDigit(codePoint)) {
            break;
        }
        index += Character.charCount(codePoint);
    }

    return index;
}

From source file:org.mariotaku.twidere.util.CodePointArray.java

public int charCount(int start, int end) {
    int count = 0;
    for (int i = start; i < end; i++) {
        count += Character.charCount(codePoints[i]);
    }// w w w  .j  a  va 2 s.  c o m
    return count;
}

From source file:Main.java

/**
 * Escapes a string builder so that it is valid XML.
 * //from   w ww  .  j a v a  2s .  c  om
 * @param sb
 *        The string builder to escape.
 */
public static void escapeXML(StringBuilder sb) {
    // double quote -- quot
    // ampersand -- amp
    // less than -- lt
    // greater than -- gt
    // apostrophe -- apos
    for (int i = 0; i < sb.length();) {
        int codePoint = Character.codePointAt(sb, i);
        int length = Character.charCount(codePoint);
        if (codePoint == '<') {
            sb.replace(i, i + length, LT);
            i += LT.length();
        } else if (codePoint == '>') {
            sb.replace(i, i + length, GT);
            i += GT.length();
        } else if (codePoint == '\"') {
            sb.replace(i, i + length, QUOT);
            i += QUOT.length();
        } else if (codePoint == '&') {
            sb.replace(i, i + length, AMP);
            i += AMP.length();
        } else if (codePoint == '\'') {
            sb.replace(i, i + length, APOS);
            i += APOS.length();
        } else {
            i += length;
        }
    }
}

From source file:android.support.text.emoji.EmojiProcessor.java

EmojiMetadata getEmojiMetadata(@NonNull final CharSequence charSequence) {
    final ProcessorSm sm = new ProcessorSm(mMetadataRepo.getRootNode());
    final int end = charSequence.length();
    int currentOffset = 0;

    while (currentOffset < end) {
        final int codePoint = Character.codePointAt(charSequence, currentOffset);
        final int action = sm.check(codePoint);
        if (action != ACTION_ADVANCE_END) {
            return null;
        }/*from w  ww .  jav  a 2  s  .c  o  m*/
        currentOffset += Character.charCount(codePoint);
    }

    if (sm.isInFlushableState()) {
        return sm.getCurrentMetadata();
    }

    return null;
}

From source file:uk.ac.bbsrc.tgac.miso.integration.util.IntegrationUtils.java

/**
 * Sends a String message to a given host socket
 * //from  w  w  w  .  jav a 2s .c  o  m
 * @param socket
 *          of type Socket
 * @param query
 *          of type String
 * @return String
 * @throws IntegrationException
 *           when the socket couldn't be created
 */
public static String sendMessage(Socket socket, String query) throws IntegrationException {
    BufferedWriter wr = null;
    BufferedReader rd = null;
    try {
        wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));

        // Send data
        wr.write(query + "\r\n");
        wr.flush();

        // Get response
        rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        wr.close();
        rd.close();

        String dirty = sb.toString();
        StringBuilder response = new StringBuilder();
        int codePoint;
        int i = 0;
        while (i < dirty.length()) {
            codePoint = dirty.codePointAt(i);
            if ((codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD)
                    || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                    || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                    || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF))) {
                response.append(Character.toChars(codePoint));
            }
            i += Character.charCount(codePoint);
        }

        return response.toString().replace("\\\n", "").replace("\\\t", "");
    } catch (UnknownHostException e) {
        log.error("Cannot resolve host: " + socket.getInetAddress(), e);
        throw new IntegrationException(e.getMessage());
    } catch (IOException e) {
        log.error("Couldn't get I/O for the connection to: " + socket.getInetAddress(), e);
        throw new IntegrationException(e.getMessage());
    } finally {
        try {
            if (wr != null) {
                wr.close();
            }
            if (rd != null) {
                rd.close();
            }
        } catch (Throwable t) {
            log.error("close socket", t);
        }
    }
}

From source file:nz.ac.otago.psyanlab.common.designer.program.operand.RenameOperandDialogueFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Bundle args = getArguments();/*from   w w w . j a  v a  2 s.c  o  m*/
    if (args != null) {
        mOperandId = args.getLong(ARG_OPERAND_ID, -1);
    }

    if (mOperandId == -1) {
        throw new RuntimeException("Invalid operand id.");
    }

    mOperand = mCallbacks.getOperand(mOperandId);

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.dialogue_rename_variable, null);
    mName = (EditText) view.findViewById(R.id.name);
    mName.setText(mOperand.getName());

    // Thanks to serwus <http://stackoverflow.com/users/1598308/serwus>,
    // who posted at <http://stackoverflow.com/a/20325852>. Modified to
    // support unicode codepoints and validating first character of input.
    InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            boolean keepOriginal = true;
            StringBuilder sb = new StringBuilder(end - start);

            int offset = 0;
            String s = source.toString();

            while (offset < s.length()) {
                final int codePoint = s.codePointAt(offset);
                if ((offset == 0 && isAllowedAsFirst(codePoint)) || (offset > 0 && isAllowed(codePoint))) {
                    sb.appendCodePoint(codePoint);
                } else {
                    keepOriginal = false;
                }
                offset += Character.charCount(codePoint);
            }

            if (keepOriginal)
                return null;
            else {
                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(sb);
                    TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                    return sp;
                } else {
                    return sb;
                }
            }
        }

        private boolean isAllowed(int codePoint) {
            return Character.isLetterOrDigit(codePoint);
        }

        private boolean isAllowedAsFirst(int codePoint) {
            return Character.isLetter(codePoint);
        }
    };

    mName.setFilters(new InputFilter[] { filter });

    // Build dialogue.
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(getString(R.string.title_rename_variable, mOperand.getName())).setView(view)
            .setPositiveButton(R.string.action_rename, mPositiveListener)
            .setNegativeButton(R.string.action_cancel, mNegativeListener);

    // Create the AlertDialog object and return it
    Dialog dialog = builder.create();
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    return dialog;
}

From source file:org.apache.any23.extractor.calendar.BaseCalendarExtractor.java

private static String camelCase(String name, boolean forProperty) {
    String[] nameComponents = name.toLowerCase(Locale.ENGLISH).split("-");
    StringBuilder sb = new StringBuilder(name.length());
    int i = 0;/*from w w  w .  jav  a2s  .  c o  m*/
    if (forProperty) {
        sb.append(nameComponents[i++]);
    }
    for (int len = nameComponents.length; i < len; i++) {
        String n = nameComponents[i];
        if (!n.isEmpty()) {
            int ind = Character.charCount(n.codePointAt(0));
            sb.append(n.substring(0, ind).toUpperCase(Locale.ENGLISH)).append(n.substring(ind));
        }
    }
    return sb.toString();
}

From source file:app.data.parse.WebPageUtil.java

/**
 * ???//  ww w  .  ja  va 2  s.  c om
 */
public static String ellipsis(String text, int limit, @NotNull String append) {
    if (text.length() <= limit) {
        return text;
    }

    final int space = limit - append.length();
    int i = 0, next = 0;
    while (i + next <= space) {
        i += next;
        int unicode = Character.codePointAt(text, i);
        next = Character.charCount(unicode);
    }
    return text.substring(0, i) + append;
}

From source file:org.wso2.carbon.appmgt.hostobjects.HostObjectUtils.java

/**
 * Returns the text (key {@code text}) and color (key {@code color}) of the default thumbnail based on the specified app name.
 * @param appName app name/*from  www. j  av a 2 s  . c om*/
 * @return default thumbnail data
 * @exception IllegalArgumentException if {@code appName} is {@code null} or empty
 */
public static Map<String, String> getDefaultThumbnail(String appName) {
    if (appName == null) {
        throw new IllegalArgumentException("Invalid argument. App name cannot be null.");
    }
    if (appName.isEmpty()) {
        throw new IllegalArgumentException("Invalid argument. App name cannot be empty.");
    }

    String defaultThumbnailText;
    if (appName.length() == 1) {
        // only one character in the app name
        defaultThumbnailText = appName;
    } else {
        // there are more than one character in the app name
        String[] wordsInAppName = StringUtils.split(appName);
        int firstCodePoint, secondCodePoint;
        if (wordsInAppName.length == 1) {
            // one word
            firstCodePoint = Character.toTitleCase(wordsInAppName[0].codePointAt(0));
            secondCodePoint = wordsInAppName[0].codePointAt(Character.charCount(firstCodePoint));
        } else {
            // two or more words
            firstCodePoint = Character.toTitleCase(wordsInAppName[0].codePointAt(0));
            secondCodePoint = wordsInAppName[1].codePointAt(0);
        }
        defaultThumbnailText = (new StringBuffer()).append(Character.toChars(firstCodePoint))
                .append(Character.toChars(secondCodePoint)).toString();
    }
    String defaultThumbnailColor = DEFAULT_THUMBNAIL_COLORS[Math.abs(appName.hashCode())
            % DEFAULT_THUMBNAIL_COLORS.length];

    Map<String, String> defaultThumbnail = new HashMap<String, String>(2);
    defaultThumbnail.put("text", defaultThumbnailText);
    defaultThumbnail.put("color", defaultThumbnailColor);
    return defaultThumbnail;
}

From source file:org.apache.bval.jsr.util.PathNavigation.java

private static String parseQuotedString(CharSequence path, PathPosition pos) throws Exception {
    int len = path.length();
    int start = pos.getIndex();
    if (start < len) {
        char quote = path.charAt(start);
        pos.next();/*  w ww. j  a v  a2  s .c  om*/
        StringWriter w = new StringWriter();
        while (pos.getIndex() < len) {
            int here = pos.getIndex();
            // look for matching quote
            if (path.charAt(here) == quote) {
                pos.next();
                return w.toString();
            }
            int codePoints = StringEscapeUtils.UNESCAPE_JAVA.translate(path, here, w);
            if (codePoints == 0) {
                w.write(Character.toChars(Character.codePointAt(path, here)));
                pos.next();
            } else {
                for (int i = 0; i < codePoints; i++) {
                    pos.plus(Character.charCount(Character.codePointAt(path, pos.getIndex())));
                }
            }
        }
        // if reached, reset due to no ending quote found
        pos.setIndex(start);
    }
    return null;
}