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:com.cohort.util.String2.java

/**
 * This extracts the lower 8 bits of each char to form a
 * byte array./*from w  ww.  j  a v  a  2  s  .  c o  m*/
 *
 * @param sb a StringBuilder
 * @return the corresponding byte[] (or null if s is null)
 */
public static byte[] toByteArray(StringBuilder sb) {
    if (sb == null)
        return null;
    int sbLength = sb.length();
    byte[] ba = new byte[sbLength];
    for (int i = 0; i < sbLength; i++) {
        char c = sb.charAt(i); //2016-11-29 I added: char>255 -> 255, it's better than just low 8 bits
        ba[i] = (byte) (c < 256 ? c : 255);
    }
    return ba;
}

From source file:com.cohort.util.String2.java

/**
 * Returns a string where all cases of more than one space are 
 * replaced by one space.  The string is also trim'd to remove
 * leading and trailing spaces.// w  ww.j  a  v  a  2  s .  c  o  m
 * Also, spaces after { or ( and before ) or } will be removed.
 *
 * @param s 
 * @return s, but with the spaces combined
 *    (or null if s is null)
 */
public static String combineSpaces(String s) {
    if (s == null)
        return null;
    s = s.trim();
    int sLength = s.length();
    if (sLength <= 2) //first and last chars must be non-space
        return s;
    StringBuilder sb = new StringBuilder(sLength);
    sb.append(s.charAt(0));
    for (int po = 1; po < sLength; po++) {
        char ch = s.charAt(po);
        if (ch == ' ') {
            if ("{( ".indexOf(sb.charAt(sb.length() - 1)) < 0) //prev isn't {( or ' '
                sb.append(ch);
        } else if (")}".indexOf(ch) >= 0 && sb.charAt(sb.length() - 1) == ' ') {
            sb.setCharAt(sb.length() - 1, ch); // ) overwrite previous ' '
        } else {
            sb.append(ch);
        }
    }
    return sb.toString();
}

From source file:com.funambol.foundation.items.dao.DataBaseFileDataObjectMetadataDAO.java

/**
 * Updates file data object metadata. <code>content</code> is not used.
 * @param fdow/*ww w  .  j  a  v  a2  s  .c om*/
 * @throws com.funambol.foundation.exception.DAOException
 */
public void updateItem(FileDataObjectWrapper fdow) throws DAOException {

    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {

        FileDataObject fdo = fdow.getFileDataObject();
        Long fdoId = Long.valueOf(fdow.getId());

        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        StringBuilder updateQuery = new StringBuilder();

        updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_BEGIN);

        updateQuery.append(SQL_FIELD_LAST_UPDATE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        updateQuery.append(SQL_FIELD_STATUS).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        updateQuery.append(SQL_FIELD_UPLOAD_STATUS).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        String localName = fdow.getLocalName();
        if (localName != null) {
            updateQuery.append(SQL_FIELD_LOCAL_NAME).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        } else {
            // if the item was deleted and readded again with a sync
            // considering only the metadata, the local name must be set to
            // null, since the previous file was already deleted and the new
            // file would be uploaded later.
            updateQuery.append(SQL_FIELD_LOCAL_NAME).append(SQL_EQUALS_NULL_COMMA);
        }

        Long crc = Long.valueOf(fdow.getFileDataObject().getCrc());
        updateQuery.append(SQL_FIELD_CRC).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        String trueName = fdo.getName();
        if (trueName != null) {
            updateQuery.append(SQL_FIELD_TRUE_NAME).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        MediaUtils.setFDODates(fdo, fdo.getCreated(), fdo.getModified());

        Timestamp created = timestamp(fdo.getCreated());
        if (created == null) {
            created = currentTime;
        }

        Timestamp modified = timestamp(fdo.getModified());
        if (modified == null) {
            modified = currentTime;
        }
        updateQuery.append(SQL_FIELD_CREATED).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        updateQuery.append(SQL_FIELD_MODIFIED).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        Timestamp accessed = timestamp(fdo.getAccessed());
        if (accessed != null) {
            updateQuery.append(SQL_FIELD_ACCESSED).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Boolean hidden = fdo.getHidden();
        if (hidden != null) {
            updateQuery.append(SQL_FIELD_H).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Boolean system = fdo.getSystem();
        if (system != null) {
            updateQuery.append(SQL_FIELD_S).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Boolean archived = fdo.getArchived();
        if (archived != null) {
            updateQuery.append(SQL_FIELD_A).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Boolean deleted = fdo.getDeleted();
        if (deleted != null) {
            updateQuery.append(SQL_FIELD_D).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Boolean writable = fdo.getWritable();
        if (writable != null) {
            updateQuery.append(SQL_FIELD_W).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Boolean readable = fdo.getReadable();
        if (readable != null) {
            updateQuery.append(SQL_FIELD_R).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Boolean executable = fdo.getExecutable();
        if (executable != null) {
            updateQuery.append(SQL_FIELD_X).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String contentType = fdo.getContentType();
        if (contentType != null) {
            updateQuery.append(SQL_FIELD_CTTYPE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Long size = fdo.getSize();
        if (size != null) {
            updateQuery.append(SQL_FIELD_SIZE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Long sizeOnStorage = fdow.getSizeOnStorage();
        if (sizeOnStorage != null) {
            updateQuery.append(SQL_FIELD_SIZE_ON_STORAGE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        if (updateQuery.charAt(updateQuery.length() - 2) == ',') {
            updateQuery.deleteCharAt(updateQuery.length() - 2);
        }

        updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_END);

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        ps = con.prepareStatement(updateQuery.toString());

        int k = 1;

        Timestamp lastUpdate = (fdow.getLastUpdate() == null) ? currentTime : fdow.getLastUpdate();
        ps.setLong(k++, lastUpdate.getTime());

        ps.setString(k++, String.valueOf(Def.PIM_STATE_UPDATED));
        ps.setString(k++, String.valueOf(fdo.getUploadStatus()));

        if (localName != null) {
            ps.setString(k++, StringUtils.left(localName, SQL_LOCAL_NAME_DIM));
        }

        ps.setLong(k++, crc);

        if (trueName != null) {
            ps.setString(k++, StringUtils.left(trueName, SQL_TRUE_NAME_DIM));
        }

        // cannot be null
        ps.setTimestamp(k++, created);
        ps.setTimestamp(k++, modified);

        if (accessed != null) {
            ps.setTimestamp(k++, accessed);
        }

        if (hidden != null) {
            ps.setString(k++, hidden ? ONE : NIL);
        }

        if (system != null) {
            ps.setString(k++, system ? ONE : NIL);
        }

        if (archived != null) {
            ps.setString(k++, archived ? ONE : NIL);
        }

        if (deleted != null) {
            ps.setString(k++, deleted ? ONE : NIL);
        }

        if (writable != null) {
            ps.setString(k++, writable ? ONE : NIL);
        }

        if (readable != null) {
            ps.setString(k++, readable ? ONE : NIL);
        }

        if (executable != null) {
            ps.setString(k++, executable ? ONE : NIL);
        }

        if (contentType != null) {
            ps.setString(k++, StringUtils.left(contentType, SQL_CTTYPE_DIM));
        }

        if (size != null) {
            ps.setLong(k++, size);
        }

        if (sizeOnStorage != null) {
            ps.setLong(k++, sizeOnStorage);
        }

        ps.setLong(k++, fdoId);
        ps.setString(k++, userId);
        ps.setString(k++, sourceURI);

        ps.executeUpdate();

        // delete and add the properties associated to the new FDO
        removeAllProperties(fdow.getId());
        addProperties(fdow);

    } catch (Exception e) {
        throw new DAOException("Error updating file data object.", e);
    } finally {
        DBTools.close(con, ps, rs);
    }
}

From source file:com.cohort.util.String2.java

/** This suggests a camel-case variable name.
 * /*  w w w.  j  av  a 2 s . co m*/
 * @param s the starting string for the variable name.
 * @return a valid variable name asciiLowerCaseLetter+asciiDigitLetter*, using camel case.
 *   This is a simplistic suggestion. Different strings may return the same variable name.
 *   null returns "null".
 *   "" returns "a".
 */
public static String toVariableName(String s) {
    if (s == null)
        return "null";
    int sLength = s.length();
    if (sLength == 0)
        return "a";
    s = modifyToBeASCII(s);
    s = toTitleCase(s);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < sLength; i++) {
        char c = s.charAt(i);
        if (isDigitLetter(c))
            sb.append(c);
    }
    if (sb.length() == 0)
        return "a";
    char c = sb.charAt(0);
    sb.setCharAt(0, Character.toLowerCase(c));
    if (c >= '0' && c <= '9')
        sb.insert(0, 'a');
    return sb.toString();
}

From source file:com.cohort.util.String2.java

/**
 * Finds the first instance of s at or after fromIndex (0.. ) in sb.
 *
 * @param sb a StringBuilder/*from  ww w. ja va2s . c  o m*/
 * @param s the String you want to find
 * @param fromIndex the index number of the position to start the search
 * @return The starting position of s. If s is null or not found, it returns -1.
 */
public static int indexOf(StringBuilder sb, String s, int fromIndex) {
    if (s == null)
        return -1;
    int sLength = s.length();
    if (sLength == 0)
        return -1;

    char ch = s.charAt(0);
    int index = Math.max(fromIndex, 0);
    int tSize = sb.length() - sLength + 1; //no point in searching last few char
    while (index < tSize) {
        if (sb.charAt(index) == ch) {
            int nCharsMatched = 1;
            while ((nCharsMatched < sLength) && (sb.charAt(index + nCharsMatched) == s.charAt(nCharsMatched)))
                nCharsMatched++;
            if (nCharsMatched == sLength)
                return index;
        }

        index++;
    }

    return -1;
}

From source file:com.cohort.util.String2.java

/**
 * This is like modifyToBeFileNameSafe, but restricts the name to:
 * <ul>/* w ww  . j  a v  a 2 s  . c  o  m*/
 * <li>first character must be (iso8859Letter|_).
 * <li>subsequent characters must be (iso8859Letter|_|0-9).
 * </ul>
 * Note that Java allows Unicode characters, but this does not.
 * See also the safer encodeMatlabNameSafe(String s).
 * Note, this does not check for names that are too long
 * (many system have an 80 or 255 char limit).
 *
 * @param s
 * @return a safe variable name (but perhaps two s's lead to the same result)
 */
public static String modifyToBeVariableNameSafe(String s) {
    if (isVariableNameSafe(s))
        return s;
    if (s == null)
        return "_null";
    s = replaceAll(s, "%20", "_");
    if (s.indexOf("%3a") >= 0) {
        s = replaceAll(s, "CF%3afeature_type", "featureType"); //CF:feature_type
        s = replaceAll(s, "CF%3a", ""); //CF:
        s = replaceAll(s, "%3a", "_");
    }
    int n = s.length();
    if (n == 0)
        return "_";

    StringBuilder sb = new StringBuilder(n + 1);

    //first character must be (iso8859Letter|_)
    char ch = s.charAt(0);
    sb.append(isLetter(ch) ? ch : isDigit(ch) ? "_" + ch : "_");

    //subsequent characters must be (iso8859Letter|_|0-9)
    for (int i = 1; i < n; i++) {
        ch = s.charAt(i);
        if (isDigitLetter(ch))
            sb.append(ch);
        else if (sb.charAt(sb.length() - 1) != '_')
            sb.append('_');
    }

    //remove trailing _
    if (sb.length() > 1 && sb.charAt(sb.length() - 1) == '_')
        sb.setLength(sb.length() - 1);

    return sb.toString();
}

From source file:com.cohort.util.String2.java

/**
 * This is like combineSpaces, but converts any sequence of whitespace
 * to be one space.  The string is also trim'd to remove
 * leading and trailing whitespace./* w ww. j a v  a  2 s.c om*/
 * Also, spaces after { or ( and before ) or } will be removed.
 *
 * @param sb 
 */
public static void whitespacesToSpace(StringBuilder sb) {
    if (sb == null)
        return;
    String s = sb.toString().trim(); //this removes whitespace, not just ' '
    int sLength = s.length();
    sb.setLength(0);
    if (sLength == 0)
        return;
    sb.append(s.charAt(0));
    for (int po = 1; po < sLength; po++) {
        char ch = s.charAt(po);
        if (Character.isWhitespace(ch)) {
            char ch2 = sb.charAt(sb.length() - 1);
            if (!(ch2 == '{' || ch2 == '(' || ch2 == ' ')) //prev isn't {( or ' '
                sb.append(' ');
        } else if ((ch == ')' || ch == '}') && sb.charAt(sb.length() - 1) == ' ') {
            sb.setCharAt(sb.length() - 1, ch); // ) overwrite previous ' '
        } else {
            sb.append(ch);
        }
    }
}

From source file:com.cohort.util.String2.java

/**
 * Replaces all occurences of <tt>oldS</tt> in sb with <tt>newS</tt>.
 * If <tt>oldS</tt> occurs inside <tt>newS</tt>, it won't be replaced
 *   recursively (obviously)./*from w w  w.  j a va  2 s  .  c  o m*/
 * 
 * @param sb the StringBuilder
 * @param oldS the string to be searched for
 * @param newS the string to replace oldS
 * @param ignoreCase   If true, when searching sb for oldS, this ignores the case of sb and oldS.
 * @return the number of replacements made.
 */
public static int replaceAll(StringBuilder sb, String oldS, String newS, boolean ignoreCase) {
    int sbL = sb.length();
    int oldSL = oldS.length();
    if (oldSL == 0)
        return 0;
    int newSL = newS.length();
    StringBuilder testSB = sb;
    String testOldS = oldS;
    if (ignoreCase) {
        testSB = new StringBuilder(sbL);
        for (int i = 0; i < sbL; i++)
            testSB.append(Character.toLowerCase(sb.charAt(i)));
        testOldS = oldS.toLowerCase();
    }
    int po = testSB.indexOf(testOldS);
    //System.out.println("testSB=" + testSB.toString() + " testOldS=" + testOldS + " po=" + po); //not String2.log
    if (po < 0)
        return 0;
    StringBuilder sb2 = new StringBuilder(sbL / 5 * 6); //a little bigger
    int base = 0;
    int n = 0;
    while (po >= 0) {
        n++;
        sb2.append(sb.substring(base, po));
        sb2.append(newS);
        base = po + oldSL;
        po = testSB.indexOf(testOldS, base);
        //System.out.println("testSB=" + testSB.toString() + " testOldS=" + testOldS + " po=" + po + 
        //    " sb2=" + sb2.toString()); //not String2.log
    }
    sb2.append(sb.substring(base));
    sb.setLength(0);
    sb.append(sb2);
    return n;
}

From source file:com.cohort.util.String2.java

/**
 * This is like noLongLines, but will only break (add newlines) at spaces.
 * If there is no reasonable break before maxLength, it will break after maxLength.
 *
 * @param sb a StringBuilder with multiple lines, separated by \n's
 * @param maxLength the maximum line length allowed
 * @param spaces the string to be inserted after the inserted newline, e.g., "&lt;br&gt;    " 
 * @return the same or a different StringBuilder, but with no long lines
 *///from   w  w  w .  ja va2s .c  o  m
public static StringBuilder noLongLinesAtSpace(StringBuilder sb, int maxLength, String spaces) {
    int sbLength = sb.length();
    if (sbLength <= maxLength)
        return sb;
    StringBuilder newSB = new StringBuilder(sbLength / 5 * 6);
    int minCount = maxLength / 2; //try hard

    int startAt = 0; //start for next copy chunk
    int count = 0; //don't jump ahead because there may be an internal \n
    int lastSpaceAt = -1;

    for (int sbi = 0; sbi < sbLength; sbi++) {
        char ch = sb.charAt(sbi);
        if (ch == '\n') {
            newSB.append(sb, startAt, sbi + 1);
            startAt = sbi + 1;
            count = 0;
            lastSpaceAt = -1;
        } else {
            if (ch == ' ' && count >= minCount)
                lastSpaceAt = sbi;
            count++;
            if (count >= maxLength && lastSpaceAt >= 0) {

                //use lastSpaceAt
                newSB.append(sb, startAt, lastSpaceAt);
                newSB.append('\n');
                newSB.append(spaces);
                sbi = lastSpaceAt;
                lastSpaceAt = -1;
                count = spaces.length();

                //maybe next char is a space, too; skip to last space in a series
                while (sbi < sbLength - 1 && sb.charAt(sbi + 1) == ' ')
                    sbi++;
                startAt = sbi + 1;
            }
        }
    }
    //copy remainder of sb
    if (startAt < sbLength)
        newSB.append(sb, startAt, sbLength);
    return newSB;
}

From source file:com.arksoft.epamms.ZGlobal1_Operation.java

int ConvertCharacterString(StringBuilder sbTarget, StringBuilder sbSource, StringBuilder sbOrigMemory,
        int nFileType) // 1-Text   2-HTML
{
    char ch;/*www . j  a  va 2s.  com*/
    int lTabCount;
    int i; // index to sbTarget
    int j; // index to sbSource
    int k;

    // This code checks for "carriage return/line feed" combinations in the
    // text and inserts the correct \par and \tab strings in the target text.
    // pchTarget = *sbTarget;

    // First, determine if the start of the text is preceded by tab characters and if so, count them.
    lTabCount = 0;

    /** TODO - figure this out and implement java version
    String pchBack = sbOrigMemory - 5;
    while ( zstrncmp( sbOrigMemory, "\\tab", 4 ) == 0 )
    {
       lTabCount++;
       pchBack = pchBack - 5;
    }
     **/

    // Copy the characters, inserting \par and \tab strings as necessary for new lines.
    for (i = 0, j = 0; (ch = sbSource.charAt(j)) != '\0'; j++) {
        // Search for carriage return/line feed and insert \par and \tab strings.
        if (ch == 13 && sbSource.charAt(j + 1) == 10) {
            // Copy carriage control and line feed characters.
            sbTarget.setCharAt(i++, sbSource.charAt(j++));
            sbTarget.setCharAt(i++, sbSource.charAt(j++));

            // Insert \par and \tab characters.
            if (nFileType == 1) {
                i = zstrcpy(sbTarget, i, "\\par ");
            } else {
                i = zstrcpy(sbTarget, i, "<br />");
            }

            for (k = 0; k < lTabCount; k++) {
                i = zstrcpy(sbTarget, i, "\\tab ");
            }
        } else {
            sbTarget.setCharAt(i++, sbSource.charAt(j++));
        }
    }

    sbTarget.setCharAt(i++, '\0');

    return (0);
}