Example usage for java.lang StringBuilder charAt

List of usage examples for java.lang StringBuilder charAt

Introduction

In this page you can find the example usage for java.lang StringBuilder charAt.

Prototype

char charAt(int index);

Source Link

Document

Returns the char value at the specified index.

Usage

From source file:org.folg.names.score.DMSoundex.java

/**
 *
 * @param s must be romanized and in lower case
 * @return//  ww  w .  j  a  v a  2s.  co m
 */
public String encode(String s) {
    StringBuilder buf = new StringBuilder();
    int pos = 0;
    boolean atBegin = true;
    boolean prevSkipped = false;
    while (pos < s.length() && buf.length() < maxCodeLength) {
        boolean found = false;
        for (int len = Math.min(s.length() - pos, MAX_CODE_LEN); len > 0; len--) {
            int nextPos = pos + len;
            String token = s.substring(pos, nextPos);
            String code = null;
            if (atBegin) {
                code = startCodeMaps[len - 1].get(token);
            } else if (nextPos < s.length() && Arrays.binarySearch(VOWELS, s.charAt(nextPos)) >= 0) {
                code = beforeVowelCodeMaps[len - 1].get(token);
            } else {
                code = otherCodeMaps[len - 1].get(token);
            }
            if (code != null) {
                if (prevSkipped || code.length() != 1 || buf.length() == 0
                        || buf.charAt(buf.length() - 1) != code.charAt(0)) {
                    buf.append(code);
                }
                pos = nextPos;
                found = true;
                break;
            }
        }
        atBegin = false;
        if (found) {
            prevSkipped = false;
        } else {
            prevSkipped = true;
            pos++;
        }
    }
    if (buf.length() > maxCodeLength) {
        buf.setLength(maxCodeLength);
    }
    return buf.toString();
}

From source file:org.apache.hadoop.yarn.server.nodemanager.util.CgroupsLCEResourcesHandlerGPU.java

public String getResourcesOption(ContainerId containerId) {
    String containerName = containerId.toString();

    StringBuilder sb = new StringBuilder("cgroups=");

    if (isCpuWeightEnabled()) {
        sb.append(pathForCgroup(CONTROLLER_CPU, containerName) + "/tasks");
        sb.append(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR);
    }/*from w w  w .  j  a  va  2  s.c  o m*/

    sb.append(pathForCgroup(CONTROLLER_DEVICES, containerName) + "/tasks");
    sb.append(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR);

    if (sb.charAt(sb.length() - 1) == PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR) {
        sb.deleteCharAt(sb.length() - 1);
    }

    return sb.toString();
}

From source file:de.micromata.genome.gwiki.page.impl.wiki.GWikiMacroFragment.java

public void getMacroSource(StringBuilder sb, GWikiFragment parent, GWikiFragment previous, GWikiFragment next) {
    appendPrevNlIfNeeded(sb, parent, previous, this);
    renderSourceHead(sb);//from  ww w. j  av  a 2 s . c  o  m
    if (macro.hasBody() == false) {
        if (GWikiMacroRenderFlags.NewLineAfterEnd.isSet(macro.getRenderModes()) == true) {
            sb.append("\n");
        }
        return;
    }
    if (GWikiMacroRenderFlags.NewLineAfterStart.isSet(macro.getRenderModes()) == true) {
        sb.append("\n");
    }
    if (macro.evalBody() == true) {
        if (attrs.getChildFragment() != null && attrs.getChildFragment().getChilds().size() > 0) {
            attrs.getChildFragment().getSource(sb);
        }
    } else {
        sb.append(attrs.getBody());
    }

    if (GWikiMacroRenderFlags.NewLineBeforeEnd.isSet(macro.getRenderModes()) == true) {
        if (sb.charAt(sb.length() - 1) != '\n') {
            sb.append("\n");
        }
    }
    renderSourceFoot(sb);

}

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

static void corrupt(List<File> files) throws IOException {
    for (File f : files) {
        StringBuilder content = new StringBuilder(DFSTestUtil.readFile(f));
        char c = content.charAt(0);
        content.setCharAt(0, ++c);//from w  w  w  . j  a va  2  s. c  om
        PrintWriter out = new PrintWriter(f);
        out.print(content);
        out.flush();
        out.close();
    }
}

From source file:org.apache.openjpa.jdbc.meta.ReverseMappingTool.java

/**
 * Replace characters not allowed in Java names with an underscore;
 * package-private for testing./*from  www.  ja v  a  2  s. co  m*/
 */
static String replaceInvalidCharacters(String str) {
    if (StringUtils.isEmpty(str))
        return str;

    StringBuilder buf = new StringBuilder(str);
    char c;
    for (int i = 0; i < buf.length(); i++) {
        c = buf.charAt(i);
        if (c == '$' || !Character.isJavaIdentifierPart(str.charAt(i)))
            buf.setCharAt(i, '_');
    }

    // strip leading and trailing underscores
    int start = 0;
    while (start < buf.length() && buf.charAt(start) == '_')
        start++;
    int end = buf.length() - 1;
    while (end >= 0 && buf.charAt(end) == '_')
        end--;

    // possible that all chars in name are invalid
    if (start > end)
        return "x";
    return buf.substring(start, end + 1);
}

From source file:com.github.mybatis.spring.MapperFactoryBean.java

private void evalArray(Object arr, StringBuilder sbd) {
    int sz = Array.getLength(arr);
    if (sz == 0) {
        sbd.append("[]");
        return;/* w  w w  .  ja v a 2  s.c  o  m*/
    }
    Class<?> clz = Array.get(arr, 0).getClass();
    if (clz == Byte.class) {
        sbd.append("Byte[").append(sz).append(']');
        return;
    }
    if (isPrimitive(clz)) {
        sbd.append('[');
        int len = Math.min(sz, 10);
        for (int i = 0; i < len; i++) {
            Object obj = Array.get(arr, i);
            if (isPrimitive(obj.getClass())) {
                sbd.append(evalPrimitive(obj));
            } else {
                sbd.append(obj.getClass().getSimpleName()).append(":OBJ");
            }
            sbd.append(',');
        }
        if (sz > 10) {
            sbd.append(",...,len=").append(sz);
        }
        if (sbd.charAt(sbd.length() - 1) == ',') {
            sbd.setCharAt(sbd.length() - 1, ']');
        } else {
            sbd.append(']');
        }
    } else {
        sbd.append("[len=").append(sz).append(']');
    }
}

From source file:aldenjava.opticalmapping.data.data.OptMapDataReader.java

private DataNode parseFA01() throws IOException {
    if (nextline == null)
        return null;
    String name = nextline.substring(1);
    StringBuilder zeroOneString = new StringBuilder();
    String s;/*from  w ww . jav  a2 s  .  co m*/
    while ((s = br.readLine()) != null) {
        if (s.startsWith(">")) {
            nextline = s;
            break;
        } else
            zeroOneString = zeroOneString.append(s);
    }

    if (zeroOneString.length() == 0)
        return null;
    else {
        long ref_size = zeroOneString.length();
        long zero = 0;
        List<Long> refl = new ArrayList<Long>();
        List<Long> refp = new ArrayList<Long>();
        for (long i = 0; i < ref_size; i++) {
            if (zeroOneString.charAt((int) i) == '0')
                zero++;
            else if (zeroOneString.charAt((int) i) == '1') {
                refl.add(zero);
                refp.add(i);
                zero = 0;
            }
        }
        refl.add(zero);
        return new DataNode(name, zeroOneString.length(),
                ArrayUtils.toPrimitive(refp.toArray(new Long[refp.size()])));
    }
}

From source file:barrysw19.calculon.icc.ICCInterface.java

public void connect() throws IOException {
    connection = new Socket("chessclub.com", 23);
    doLogin();/*from  w ww  .j  a v a 2  s .  com*/
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    out = new PrintStream(connection.getOutputStream());

    send("set level1 1");
    send("set style 12");
    if (!StringUtils.isBlank(iccConfig.getFormula())) {
        send("set formula " + iccConfig.getFormula());
    }
    receiveLevel2(DgCommand.DG_MY_GAME_STARTED, DgCommand.DG_MY_GAME_RESULT, DgCommand.DG_SEND_MOVES,
            DgCommand.DG_MOVE_ALGEBRAIC, DgCommand.DG_MOVE_SMITH, DgCommand.DG_MOVE_TIME,
            DgCommand.DG_MOVE_CLOCK, DgCommand.DG_MSEC);

    setStatus();
    if (iccConfig.isReseek()) {
        reseek();
    }

    Runnable keepAlive = () -> {
        while (alive) {
            send("games *r-e-B-o-M-f-K-w-L-d-z");
            try {
                Thread.sleep(60000);
            } catch (InterruptedException x) {
                // Ignore
            }
        }
    };
    Thread keepAliveThread = new Thread(keepAlive);
    keepAliveThread.setDaemon(true);
    keepAliveThread.start();

    StringBuilder line = new StringBuilder();
    int c;
    try {
        while ((c = reader.read()) != -1) {
            lv1BlockHandler.add((char) c);

            // Ignore CTRL-M, CTRL-G
            if (c == ('M' & 0x1F) || c == ('G' & 0x1F)) {
                continue;
            }
            line.append((char) c);
            if (c == '\n') {
                fireDataReceived(line.toString());
                line.setLength(0);
                continue;
            }
            if (line.length() >= 2 && line.charAt(line.length() - 2) == ('Y' & 0x1F)
                    && line.charAt(line.length() - 1) == ']') {
                fireDataReceived(line.toString());
                line.setLength(0);
            }
        }
    } finally {
        alive = false;
        try {
            reader.close();
            out.close();
        } catch (Exception x) {
            // ignore
        }
    }
}

From source file:org.elasticsearch.index.analysis.phonetic.Nysiis.java

/**
 * Retrieves the NYSIIS code for a given String object.
 *
 * @param str String to encode using the NYSIIS algorithm
 * @return A NYSIIS code for the String supplied
 *//*  w w  w  .j  a  v  a 2 s .c  o m*/
public String nysiis(String str) {
    if (str == null) {
        return null;
    }

    // Use the same clean rules as Soundex
    str = clean(str);

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

    // Translate first characters of name:
    // MAC -> MCC, KN -> NN, K -> C, PH | PF -> FF, SCH -> SSS
    str = PAT_MAC.matcher(str).replaceFirst("MCC");
    str = PAT_KN.matcher(str).replaceFirst("NN");
    str = PAT_K.matcher(str).replaceFirst("C");
    str = PAT_PH_PF.matcher(str).replaceFirst("FF");
    str = PAT_SCH.matcher(str).replaceFirst("SSS");

    // Translate last characters of name:
    // EE -> Y, IE -> Y, DT | RT | RD | NT | ND -> D
    str = PAT_EE_IE.matcher(str).replaceFirst("Y");
    str = PAT_DT_ETC.matcher(str).replaceFirst("D");

    // First character of key = first character of name.
    StringBuilder key = new StringBuilder(str.length());
    key.append(str.charAt(0));

    // Transcode remaining characters, incrementing by one character each time
    final char[] chars = str.toCharArray();
    final int len = chars.length;

    for (int i = 1; i < len; i++) {
        final char next = i < len - 1 ? chars[i + 1] : SPACE;
        final char aNext = i < len - 2 ? chars[i + 2] : SPACE;
        final char[] transcoded = transcodeRemaining(chars[i - 1], chars[i], next, aNext);
        System.arraycopy(transcoded, 0, chars, i, transcoded.length);

        // only append the current char to the key if it is different from the last one
        if (chars[i] != chars[i - 1]) {
            key.append(chars[i]);
        }
    }

    if (key.length() > 1) {
        char lastChar = key.charAt(key.length() - 1);

        // If last character is S, remove it.
        if (lastChar == 'S') {
            key.deleteCharAt(key.length() - 1);
            lastChar = key.charAt(key.length() - 1);
        }

        if (key.length() > 2) {
            final char last2Char = key.charAt(key.length() - 2);
            // If last characters are AY, replace with Y.
            if (last2Char == 'A' && lastChar == 'Y') {
                key.deleteCharAt(key.length() - 2);
            }
        }

        // If last character is A, remove it.
        if (lastChar == 'A') {
            key.deleteCharAt(key.length() - 1);
        }
    }

    final String string = key.toString();
    return this.isStrict() ? string.substring(0, Math.min(TRUE_LENGTH, string.length())) : string;
}

From source file:org.ambraproject.wombat.service.CommentFormatting.java

private static void linkURL(StringBuilder str, String target, int maxDisplayLength) {
    String urlToDisplay;//from w w w .jav  a2  s  .  co m

    int lastEndIndex = -1; //Stores the index position, within the whole string, of the ending char of the last URL found.

    String targetString = ((target == null) || (target.trim().length() == 0)) ? ""
            : (" target=\"" + target.trim() + '\"');

    while (true) {
        int linkStartIndex = getStartUrl(str, lastEndIndex);

        //if no more links found - then end the loop
        if (linkStartIndex == -1) {
            break;
        } else {
            //Get the whole URL...
            //We move forward and add each character to the URL string until we encounter
            //an invalid URL character (we assume that the URL ends there).
            int linkEndIndex = linkStartIndex;
            String urlStr = "";

            while (true) {
                // if char at linkEndIndex is '&' then we look at the next 4 chars
                // to see if they make up "&amp;" altogether. This is the html coded
                // '&' and will pretty much stuff up an otherwise valid link becos of the ';'.
                // We therefore have to remove it before proceeding...
                if (str.charAt(linkEndIndex) == '&') {
                    if (((linkEndIndex + 6) <= str.length())
                            && "&quot;".equals(str.substring(linkEndIndex, linkEndIndex + 6))) {
                        break;
                    } else if (((linkEndIndex + 5) <= str.length())
                            && "&amp;".equals(str.substring(linkEndIndex, linkEndIndex + 5))) {
                        str.replace(linkEndIndex, linkEndIndex + 5, "&");
                    }
                }

                if (isValidURLChar(str.charAt(linkEndIndex))) {
                    urlStr += str.charAt(linkEndIndex);
                    linkEndIndex++;

                    if (linkEndIndex == str.length()) { //Reached end of str...

                        break;
                    }
                } else {
                    break;
                }
            }

            //if the characters before the linkStart equal 'href="' then don't link the url - CORE-44
            if (linkStartIndex >= 6) { //6 = "href\"".length()

                String prefix = str.substring(linkStartIndex - 6, linkStartIndex);

                if ("href=\"".equals(prefix)) {
                    lastEndIndex = linkEndIndex;

                    continue;
                }
            }

            //if the characters after the linkEnd are '</a>' then this url is probably already linked - CORE-44
            if (str.length() >= (linkEndIndex + 4)) { //4 = "</a>".length()

                String suffix = str.substring(linkEndIndex, linkEndIndex + 4);

                if ("</a>".equals(suffix)) {
                    lastEndIndex = linkEndIndex + 4;

                    continue;
                }
            }

            //Decrement linkEndIndex back by 1 to reflect the real ending index position of the URL...
            linkEndIndex--;

            // If the last char of urlStr is a '.' we exclude it. It is most likely a full stop and
            // we don't want that to be part of an url.
            while (true) {
                char lastChar = urlStr.charAt(urlStr.length() - 1);

                if (lastChar == '.') {
                    urlStr = urlStr.substring(0, urlStr.length() - 1);
                    linkEndIndex--;
                } else {
                    break;
                }
            }

            //if the URL had a '(' before it, and has a ')' at the end, trim the last ')' from the url
            //ie '(www.opensymphony.com)' => '(<a href="http://www.openymphony.com/">www.opensymphony.com</a>)'
            char lastChar = urlStr.charAt(urlStr.length() - 1);

            if (lastChar == ')') {
                if ((linkStartIndex > 0) && ('(' == (str.charAt(linkStartIndex - 1)))) {
                    urlStr = urlStr.substring(0, urlStr.length() - 1);
                    linkEndIndex--;
                }
            } else if (lastChar == '\'') {
                if ((linkStartIndex > 0) && ('\'' == (str.charAt(linkStartIndex - 1)))) {
                    urlStr = urlStr.substring(0, urlStr.length() - 1);
                    linkEndIndex--;
                }
            }
            //perhaps we ended with '&gt;', '&lt;' or '&quot;'
            //We need to strip these
            //ie '&quot;www.opensymphony.com&quot;' => '&quot;<a href="http://www.openymphony.com/">www.opensymphony.com</a>&quot;'
            //ie '&lt;www.opensymphony.com&gt;' => '&lt;<a href="http://www.openymphony.com/">www.opensymphony.com</a>&gt;'
            else if (lastChar == ';') {
                // 6 = "&quot;".length()
                if ((urlStr.length() > 6) && "&quot;".equalsIgnoreCase(urlStr.substring(urlStr.length() - 6))) {
                    urlStr = urlStr.substring(0, urlStr.length() - 6);
                    linkEndIndex -= 6;
                }
                // 4 = "&lt;".length()  || "&gt;".length()
                else if (urlStr.length() > 4) {
                    final String endingStr = urlStr.substring(urlStr.length() - 4);

                    if ("&lt;".equalsIgnoreCase(endingStr) || "&gt;".equalsIgnoreCase(endingStr)) {
                        urlStr = urlStr.substring(0, urlStr.length() - 4);
                        linkEndIndex -= 4;
                    }
                }
            }

            // we got the URL string, now we validate it and convert it into a hyperlink...

            if (maxDisplayLength > 0 && urlStr.length() > maxDisplayLength) {
                urlToDisplay = htmlEncode(urlStr.substring(0, maxDisplayLength), true) + "...";
            } else {
                urlToDisplay = htmlEncode(urlStr, true);
            }

            if (urlStr.toLowerCase().startsWith("www.")) {
                urlStr = "http://" + urlStr;
            }

            if (verifyHierarchicalURI(urlStr, null)) {
                //Construct the hyperlink for the url...
                String urlLink = "<a rel=\"nofollow\" href=\"" + urlStr + "\"" + targetString;

                if (maxDisplayLength > 0 && urlStr.length() > maxDisplayLength) {
                    urlLink += " title=\"" + htmlEncode(urlStr, true) + "\">" + urlToDisplay + "</a>";
                } else {
                    urlLink += ">" + urlToDisplay + "</a>";
                }

                //Remove the original urlStr from str and put urlLink there instead...
                str.replace(linkStartIndex, linkEndIndex + 1, urlLink);

                //Set lastEndIndex to reflect the position of the end of urlLink
                //within the whole string...
                lastEndIndex = (linkStartIndex - 1) + urlLink.length();
            } else {
                //lastEndIndex is different from the one above cos' there's no
                //<a href...> tags added...
                lastEndIndex = (linkStartIndex - 1) + urlStr.length();
            }
        }
    }
}