Example usage for java.lang StringBuffer charAt

List of usage examples for java.lang StringBuffer charAt

Introduction

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

Prototype

@Override
public synchronized char charAt(int index) 

Source Link

Usage

From source file:com.niki.normalizer.Metaphone.java

/**
 * Find the metaphone value of a String. This is similar to the
 * soundex algorithm, but better at finding similar sounding words.
 * All input is converted to upper case.
 * Limitations: Input format is expected to be a single ASCII word
 * with only characters in the A - Z range, no punctuation or numbers.
 *
 * @param txt String to find the metaphone code for
 * @return A metaphone code corresponding to the String supplied
 *///from w w  w  .  jav a2 s .  c o  m
public static String metaphone(String txt) {
    boolean hard = false;
    if ((txt == null) || (txt.length() == 0)) {
        return "";
    }
    // single character is itself
    if (txt.length() == 1) {
        return txt.toUpperCase(java.util.Locale.ENGLISH);
    }

    char[] inwd = txt.toUpperCase(java.util.Locale.ENGLISH).toCharArray();

    StringBuffer local = new StringBuffer(40); // manipulate
    StringBuffer code = new StringBuffer(10); //   output
    // handle initial 2 characters exceptions
    switch (inwd[0]) {
    case 'K':
    case 'G':
    case 'P': /* looking for KN, etc*/
        if (inwd[1] == 'N') {
            local.append(inwd, 1, inwd.length - 1);
        } else {
            local.append(inwd);
        }
        break;
    case 'A': /* looking for AE */
        if (inwd[1] == 'E') {
            local.append(inwd, 1, inwd.length - 1);
        } else {
            local.append(inwd);
        }
        break;
    case 'W': /* looking for WR or WH */
        if (inwd[1] == 'R') { // WR -> R
            local.append(inwd, 1, inwd.length - 1);
            break;
        }
        if (inwd[1] == 'H') {
            local.append(inwd, 1, inwd.length - 1);
            local.setCharAt(0, 'W'); // WH -> W
        } else {
            local.append(inwd);
        }
        break;
    case 'X': /* initial X becomes S */
        inwd[0] = 'S';
        local.append(inwd);
        break;
    default:
        local.append(inwd);
    } // now local has working string with initials fixed

    int wdsz = local.length();
    int n = 0;

    while ((code.length() < 4) && (n < wdsz)) { // max code size of 4 works well
        char symb = local.charAt(n);
        // remove duplicate letters except C
        if ((symb != 'C') && (isPreviousChar(local, n, symb))) {
            n++;
        } else { // not dup
            switch (symb) {
            case 'A':
            case 'E':
            case 'I':
            case 'O':
            case 'U':
                if (n == 0) {
                    code.append(symb);
                }
                break; // only use vowel if leading char
            case 'B':
                if (isPreviousChar(local, n, 'M') && isLastChar(wdsz, n)) { // B is silent if word ends in MB
                    break;
                }
                code.append(symb);
                break;
            case 'C': // lots of C special cases
                /* discard if SCI, SCE or SCY */
                if (isPreviousChar(local, n, 'S') && !isLastChar(wdsz, n)
                        && (FRONTV.indexOf(local.charAt(n + 1)) >= 0)) {
                    break;
                }
                if (regionMatch(local, n, "CIA")) { // "CIA" -> X
                    code.append('X');
                    break;
                }
                if (!isLastChar(wdsz, n) && (FRONTV.indexOf(local.charAt(n + 1)) >= 0)) {
                    code.append('S');
                    break; // CI,CE,CY -> S
                }
                if (isPreviousChar(local, n, 'S') && isNextChar(local, n, 'H')) { // SCH->sk
                    code.append('K');
                    break;
                }
                if (isNextChar(local, n, 'H')) { // detect CH
                    if ((n == 0) && (wdsz >= 3) && isVowel(local, 2)) { // CH consonant -> K consonant
                        code.append('K');
                    } else {
                        code.append('X'); // CHvowel -> X
                    }
                } else {
                    code.append('K');
                }
                break;
            case 'D':
                if (!isLastChar(wdsz, n + 1) && isNextChar(local, n, 'G')
                        && (FRONTV.indexOf(local.charAt(n + 2)) >= 0)) { // DGE DGI DGY -> J 
                    code.append('J');
                    n += 2;
                } else {
                    code.append('T');
                }
                break;
            case 'G': // GH silent at end or before consonant
                if (isLastChar(wdsz, n + 1) && isNextChar(local, n, 'H')) {
                    break;
                }
                if (!isLastChar(wdsz, n + 1) && isNextChar(local, n, 'H') && !isVowel(local, n + 2)) {
                    break;
                }
                if ((n > 0) && (regionMatch(local, n, "GN") || regionMatch(local, n, "GNED"))) {
                    break; // silent G
                }
                if (isPreviousChar(local, n, 'G')) {
                    // NOTE: Given that duplicated chars are removed, I don't see how this can ever be true
                    hard = true;
                } else {
                    hard = false;
                }
                if (!isLastChar(wdsz, n) && (FRONTV.indexOf(local.charAt(n + 1)) >= 0) && (!hard)) {
                    code.append('J');
                } else {
                    code.append('K');
                }
                break;
            case 'H':
                if (isLastChar(wdsz, n)) {
                    break; // terminal H
                }
                if ((n > 0) && (VARSON.indexOf(local.charAt(n - 1)) >= 0)) {
                    break;
                }
                if (isVowel(local, n + 1)) {
                    code.append('H'); // Hvowel
                }
                break;
            case 'F':
            case 'J':
            case 'L':
            case 'M':
            case 'N':
            case 'R':
                code.append(symb);
                break;
            case 'K':
                if (n > 0) { // not initial
                    if (!isPreviousChar(local, n, 'C')) {
                        code.append(symb);
                    }
                } else {
                    code.append(symb); // initial K
                }
                break;
            case 'P':
                if (isNextChar(local, n, 'H')) {
                    // PH -> F
                    code.append('F');
                } else {
                    code.append(symb);
                }
                break;
            case 'Q':
                code.append('K');
                break;
            case 'S':
                if (regionMatch(local, n, "SH") || regionMatch(local, n, "SIO")
                        || regionMatch(local, n, "SIA")) {
                    code.append('X');
                } else {
                    code.append('S');
                }
                break;
            case 'T':
                if (regionMatch(local, n, "TIA") || regionMatch(local, n, "TIO")) {
                    code.append('X');
                    break;
                }
                if (regionMatch(local, n, "TCH")) {
                    // Silent if in "TCH"
                    break;
                }
                // substitute numeral 0 for TH (resembles theta after all)
                if (regionMatch(local, n, "TH")) {
                    code.append('0');
                } else {
                    code.append('T');
                }
                break;
            case 'V':
                code.append('F');
                break;
            case 'W':
            case 'Y': // silent if not followed by vowel
                if (!isLastChar(wdsz, n) && isVowel(local, n + 1)) {
                    code.append(symb);
                }
                break;
            case 'X':
                code.append('K');
                code.append('S');
                break;
            case 'Z':
                code.append('S');
                break;
            } // end switch
            n++;
        } // end else from symb != 'C'
        if (code.length() > 4) {
            code.setLength(4);
        }
    }
    return code.toString();
}

From source file:com.wabacus.config.component.application.report.ReportDataSetValueBean.java

public String getRealDependsConditionExpression(List<AbsReportDataPojo> lstReportData) {
    if (!this.isDependentDataSet())
        return "";
    if (lstReportData == null || lstReportData.size() == 0 || this.dependsConditionExpression == null
            || this.dependsConditionExpression.trim().equals(""))
        return "";
    String realConExpress = this.dependsConditionExpression;
    DependingColumnBean dcbeanTmp;/* www . ja v a  2s  .c  o m*/
    StringBuffer parentValuesBuf = new StringBuffer();
    for (Entry<String, DependingColumnBean> entryTmp : this.mDependParents.entrySet()) {
        dcbeanTmp = entryTmp.getValue();
        for (AbsReportDataPojo dataObjTmp : lstReportData) {//?POJO?
            Object parentColVal = dataObjTmp.getColValue(dcbeanTmp.getParentColumn());
            if (parentColVal == null)
                parentColVal = "";
            if (dcbeanTmp.isVarcharType())
                parentValuesBuf.append("'");
            parentValuesBuf.append(String.valueOf(parentColVal));
            if (dcbeanTmp.isVarcharType())
                parentValuesBuf.append("'");
            parentValuesBuf.append(",");
        }
        if (parentValuesBuf.length() > 0 && parentValuesBuf.charAt(parentValuesBuf.length() - 1) == ',') {
            parentValuesBuf.deleteCharAt(parentValuesBuf.length() - 1);
        }
        if (parentValuesBuf.length() == 0 && dcbeanTmp.isVarcharType())
            parentValuesBuf.append("''");
        realConExpress = Tools.replaceAll(realConExpress,
                "#" + dcbeanTmp.getParentValueid() + "." + dcbeanTmp.getParentColumn() + "#",
                parentValuesBuf.toString());
    }
    return realConExpress;
}

From source file:net.iiit.siel.analysis.lang.LanguageIdentifier.java

/**
 * Gets the languages sampled.//from w w  w . j  a  va  2 s.  c o m
 *
 * @param content the content
 * @param index the index
 * @return the languages sampled
 */

public LanguageIdentifierConstants.LangShortNames[] getLanguagesSampled(StringBuffer content, int[] index) {

    LanguageIdentifierConstants.LangShortNames defaultLang = LanguageIdentifierConstants.LangShortNames.ENGLISH;
    LanguageIdentifierConstants.LangShortNames[] langSamples = new LanguageIdentifierConstants.LangShortNames[LanguageIdentifierConstants.totalRandomNumberTrials];
    int breakpoint = 0;
    for (int i = 0; i < index.length; i++) {

        // Check that the character is not a special character

        while ((content.charAt(index[i]) > 31 && content.charAt(index[i]) < 65)
                && breakpoint < (content.length() > 1000 ? content.length() * 0.01 : content.length() * 0.1)) {

            //  Get a new random value

            index[i] = LangIdentifierUtility.getRandomNumber(content.length() - 1);
            breakpoint++;

        }

        UnicodeBlock currentUnicode = Character.UnicodeBlock.of(content.charAt(index[i]));

        if (currentUnicode == Character.UnicodeBlock.BENGALI)
            langSamples[i] = LanguageIdentifierConstants.LangShortNames.BENGALI;
        else if (currentUnicode == Character.UnicodeBlock.TELUGU)
            langSamples[i] = LanguageIdentifierConstants.LangShortNames.TELUGU;
        else if (currentUnicode == Character.UnicodeBlock.TAMIL)
            langSamples[i] = LanguageIdentifierConstants.LangShortNames.TAMIL;
        else if (currentUnicode == Character.UnicodeBlock.DEVANAGARI)
            langSamples[i] = LanguageIdentifierConstants.LangShortNames.DEVANAGARI;
        else if (currentUnicode == Character.UnicodeBlock.GURMUKHI)
            langSamples[i] = LanguageIdentifierConstants.LangShortNames.GURMUKHI;
        else
            langSamples[i] = defaultLang;

    }

    return langSamples;
}

From source file:org.firesoa.common.jxpath.model.dom4j.Dom4JNodePointer.java

public String asPath() {
    if (id != null) {
        return "id('" + escape(id) + "')";
    }// www  .  j av a  2 s.  c o m

    StringBuffer buffer = new StringBuffer();
    if (parent != null) {

        buffer.append(parent.asPath());
    }

    if (node instanceof Element) {
        // If the parent pointer is not a JDOMNodePointer, it is
        // the parent's responsibility to produce the node test part
        // of the path
        if (parent instanceof Dom4JNodePointer) {
            if (buffer.length() == 0 || buffer.charAt(buffer.length() - 1) != '/') {
                buffer.append('/');
            }
            String nsURI = getNamespaceURI();
            String ln = Dom4JNodePointer.getLocalName((Node) node);

            if (nsURI == null) {
                buffer.append(ln);
                buffer.append('[');
                buffer.append(getRelativePositionByName()).append(']');
            } else {
                String prefix = getNamespaceResolver().getPrefix(nsURI);
                if (prefix != null) {
                    if (prefix.equals(Constants.DEFAULT_NS_PREFIX)) {
                        buffer.append(ln);
                        buffer.append('[');
                        buffer.append(getRelativePositionByName()).append(']');
                    } else {
                        buffer.append(prefix);
                        buffer.append(':');
                        buffer.append(ln);
                        buffer.append('[');
                        buffer.append(getRelativePositionByName());
                        buffer.append(']');
                    }

                } else {
                    buffer.append("node()");
                    buffer.append('[');
                    buffer.append(getRelativePositionOfElement());
                    buffer.append(']');
                }
            }

        }
    } else if (node instanceof Text || node instanceof CDATA) {
        buffer.append("/text()");
        buffer.append('[').append(getRelativePositionOfTextNode()).append(']');
    } else if (node instanceof ProcessingInstruction) {
        buffer.append("/processing-instruction(\'").append(((ProcessingInstruction) node).getTarget())
                .append("')");
        buffer.append('[').append(getRelativePositionOfPI()).append(']');
    }
    return buffer.toString();
}

From source file:architecture.common.util.TextUtils.java

/**
 * Given a string, and the index to start looking at, find the index of the
 * start of the scheme. Eg.//from  w  ww  .ja v  a 2  s  .  com
 * 
 * <pre>
 * getSchemeIndex("notes://abc", 0) -> 0
 * getSchemeIndex("abc notes://abc", 0) -> 4
 * </pre>
 * 
 * @param str
 *            The string to search for
 * @param startIndex
 *            Where to start looking at
 * @return The location the string was found, ot -1 if the string was not
 *         found.
 */
private static int getSchemeIndex(StringBuffer str, int startIndex) {
    int schemeIndex = str.indexOf(SCHEME_URL, startIndex + 1);

    // if it was not found, or found at the start of the string, then return
    // 'not found'
    if (schemeIndex <= 0) {
        return -1;
    }

    // walk backwards through the scheme until we find the first non valid
    // character
    int schemeStart;

    for (schemeStart = schemeIndex - 1; schemeStart >= 0; schemeStart--) {
        char currentChar = str.charAt(schemeStart);

        if (!isValidSchemeChar(currentChar)) {
            break;
        }
    }

    // reset the scheme to the starting character
    schemeStart++;

    // we don't want to do this, otherwise an invalid scheme would ruin the
    // linking for later schemes
    // if (UrlUtils.isValidScheme(str.substring(schemeStart, schemeIndex)))
    // return schemeStart;
    // else
    // return -1;
    return schemeStart;
}

From source file:com.wabacus.system.inputbox.AbsInputBox.java

protected void processRelativeInputBoxes() {
    if (this.lstChildids == null || this.lstChildids.size() == 0)
        return;/*from  w w w  . j ava 2  s.  c om*/
    ReportBean rbean = this.owner.getReportBean();
    if (this.displaymode == 1) {
        StringBuffer childidAndParamsBuf = new StringBuffer("{");
        AbsSelectBox childBoxObjTmp;
        boolean isConditionBox = this.owner instanceof ConditionBean;
        for (String childidTmp : this.lstChildids) {
            childidAndParamsBuf.append(childidTmp).append(":'");
            if (isConditionBox) {
                childBoxObjTmp = rbean.getChildSelectBoxInConditionById(childidTmp);
            } else {
                childBoxObjTmp = rbean.getChildSelectBoxInColById(childidTmp);
            }
            childidAndParamsBuf.append(childBoxObjTmp.getAllParentIdsAsString()).append("',");
        }
        if (childidAndParamsBuf.charAt(childidAndParamsBuf.length() - 1) == ',')
            childidAndParamsBuf.deleteCharAt(childidAndParamsBuf.length() - 1);
        childidAndParamsBuf.append("}");
        String event = getRefreshChildboxDataEventName() + "=\"reloadSelectBoxData('"
                + rbean.getPageBean().getId() + "','" + rbean.getId() + "',this,"
                + childidAndParamsBuf.toString() + "," + isConditionBox + ")\"";
        this.styleproperty = Tools.mergeHtmlTagPropertyString(this.styleproperty, event, 1);
    } else {
        String event = getRefreshChildboxDataEventName() + "=\"resetChildSelectBoxData(this)\"";
        this.styleproperty = Tools.mergeHtmlTagPropertyString(this.styleproperty, event, 1);
    }
}

From source file:org.apache.poi.ss.format.CellNumberFormatter.java

private void writeFractional(StringBuffer result, StringBuffer output) {
    int digit;/*from   w w w .j  av a2  s .  c o m*/
    int strip;
    ListIterator<Special> it;
    if (fractionalSpecials.size() > 0) {
        digit = result.indexOf(".") + 1;
        if (exponent != null)
            strip = result.indexOf("e") - 1;
        else
            strip = result.length() - 1;
        while (strip > digit && result.charAt(strip) == '0')
            strip--;
        it = fractionalSpecials.listIterator();
        while (it.hasNext()) {
            Special s = it.next();
            char resultCh = result.charAt(digit);
            if (resultCh != '0' || s.ch == '0' || digit < strip)
                output.setCharAt(s.pos, resultCh);
            else if (s.ch == '?') {
                // This is when we're in trailing zeros, and the format is '?'.  We still strip out remaining '#'s later
                output.setCharAt(s.pos, ' ');
            }
            digit++;
        }
    }
}

From source file:org.janusgraph.graphdb.database.IndexSerializer.java

public Iterable<RawQuery.Result> executeQuery(IndexQueryBuilder query, final ElementCategory resultType,
        final BackendTransaction backendTx, final StandardJanusGraphTx transaction) {
    MixedIndexType index = getMixedIndex(query.getIndex(), transaction);
    Preconditions.checkArgument(index.getElement() == resultType,
            "Index is not configured for the desired result type: %s", resultType);
    String backingIndexName = index.getBackingIndexName();
    IndexProvider indexInformation = (IndexProvider) mixedIndexes.get(backingIndexName);

    StringBuffer qB = new StringBuffer(query.getQuery());
    final String prefix = query.getPrefix();
    Preconditions.checkNotNull(prefix);//from w w w.java2s  .c o m
    //Convert query string by replacing
    int replacements = 0;
    int pos = 0;
    while (pos < qB.length()) {
        pos = qB.indexOf(prefix, pos);
        if (pos < 0)
            break;

        int startPos = pos;
        pos += prefix.length();
        StringBuilder keyBuilder = new StringBuilder();
        boolean quoteTerminated = qB.charAt(pos) == '"';
        if (quoteTerminated)
            pos++;
        while (pos < qB.length() && (Character.isLetterOrDigit(qB.charAt(pos))
                || (quoteTerminated && qB.charAt(pos) != '"') || qB.charAt(pos) == '*')) {
            keyBuilder.append(qB.charAt(pos));
            pos++;
        }
        if (quoteTerminated)
            pos++;
        int endPos = pos;
        String keyname = keyBuilder.toString();
        Preconditions.checkArgument(StringUtils.isNotBlank(keyname),
                "Found reference to empty key at position [%s]", startPos);
        String replacement;
        if (keyname.equals("*")) {
            replacement = indexInformation.getFeatures().getWildcardField();
        } else if (transaction.containsRelationType(keyname)) {
            PropertyKey key = transaction.getPropertyKey(keyname);
            Preconditions.checkNotNull(key);
            Preconditions.checkArgument(index.indexesKey(key),
                    "The used key [%s] is not indexed in the targeted index [%s]", key.name(),
                    query.getIndex());
            replacement = key2Field(index, key);
        } else {
            Preconditions.checkArgument(query.getUnknownKeyName() != null,
                    "Found reference to non-existant property key in query at position [%s]: %s", startPos,
                    keyname);
            replacement = query.getUnknownKeyName();
        }
        Preconditions.checkArgument(StringUtils.isNotBlank(replacement));

        qB.replace(startPos, endPos, replacement);
        pos = startPos + replacement.length();
        replacements++;
    }

    String queryStr = qB.toString();
    if (replacements <= 0)
        log.warn("Could not convert given {} index query: [{}]", resultType, query.getQuery());
    log.info("Converted query string with {} replacements: [{}] => [{}]", replacements, query.getQuery(),
            queryStr);
    RawQuery rawQuery = new RawQuery(index.getStoreName(), queryStr, query.getParameters());
    if (query.hasLimit())
        rawQuery.setLimit(query.getLimit());
    rawQuery.setOffset(query.getOffset());
    return Iterables.transform(backendTx.rawQuery(index.getBackingIndexName(), rawQuery),
            new Function<RawQuery.Result<String>, RawQuery.Result>() {
                @Nullable
                @Override
                public RawQuery.Result apply(@Nullable RawQuery.Result<String> result) {
                    return new RawQuery.Result(string2ElementId(result.getResult()), result.getScore());
                }
            });
}

From source file:Base64Codec.java

/**
 * /*from   ww w.  j  ava2s.c om*/
 * Base 64 Encoding works off of a 24 bit buffer.
 * It basically converts 3 bytes into 4, since normal
 * ASCII binary data is really base 256, we are stepping down
 * to base 64, therefore the number of "digits" for a single
 * number increases.
 * 
 */
public static String Encode(byte[] data, boolean newlines) {
    StringBuffer b64Data = new StringBuffer();
    int ascii, buf, padding, cnt;
    int[] b64Set;
    String b64Num;

    if (data != null) {
        cnt = 0; //MUST be set to 0 NOT 1 because the first iteration of the for i loop executes cnt++ before appending to the string buffer
        for (int i = 0; i < data.length; i += 3) {
            buf = 0;
            padding = 2;

            //First byte (will eventually become left most 8 bits in the 24-bit buffer)
            ascii = data[i] & 0xFF;
            buf = ascii;
            buf = buf << 8;

            //Second byte (will eventually become middle 8 bits in the 24-bit buffer) 
            if ((i + 1) < data.length) {
                ascii = data[i + 1] & 0xFF;
                buf = buf + ascii;
                padding--;
            }
            buf = buf << 8;

            //Third byte (will eventually become the right most 8 bits in the 24-bit buffer)
            if ((i + 2) < data.length) {
                ascii = data[i + 2] & 0xFF;
                buf = buf + ascii;
                padding--;
            }

            b64Set = ConvertToBase64Set(buf, padding); //Obtain Digit Indexes 0-63 normally, with a special 64th index for terminator value
            b64Num = ConvertToBase64Number(b64Set); //Get actual string reprentation of the 3 bytes as a base 64 number (4 bytes).

            //RFC 1421 and RFC 2045 requires a CR+LF newline every 76 characters OR ever 19 sets of 4 bytes base 64 numbers.
            if (cnt == 19) {
                cnt = 1; //Because the first iteration of the for i loop the ELSE block is executed instead, we set to 1 instead of 0.
                if (newlines) {
                    b64Data.append("\r\n"); //CR+LF
                }
            } else {
                cnt++;
            }

            b64Data.append(b64Num);
        } //End for i loop through data byte array

        //Trailing CR+LF newline if required
        if (cnt == 19 && b64Data.charAt(b64Data.length() - 1) != '=') {
            b64Data.append("\r\n"); //CR+LF
        }

    } //End data != null check

    return b64Data.toString();
}

From source file:com.jaspersoft.jasperserver.api.engine.common.service.impl.ActionModel.java

public String generateClientActionModel(ActionModelSupport actionModelInterface, Document actionModel)
        throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("{");

    Element root = actionModel.getRootElement();
    Iterator contextIt = root.getChildren().iterator();
    while (contextIt.hasNext()) {
        Element context = (Element) contextIt.next();
        //context test
        if (context.getAttributeValue(TEST_ATTR) != null) {
            if (!shouldInclude(actionModelInterface, context)) {
                continue;
            }// w w w  . j  a  va 2  s .  c  o  m
        }

        appendContext(context, sb);
        sb.append("[");
        generateChildActions(context, actionModelInterface, sb);
        sb.append("]");
        if (contextIt.hasNext()) {
            sb.append(",");
        }
    }
    int lastCharIndex = sb.length() - 1;
    if (sb.charAt(lastCharIndex) == ',') {
        sb.deleteCharAt(lastCharIndex);
    }
    sb.append("}");
    return sb.toString();
}