Example usage for java.lang StringBuilder insert

List of usage examples for java.lang StringBuilder insert

Introduction

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

Prototype

@Override
public StringBuilder insert(int offset, double d) 

Source Link

Usage

From source file:Main.java

/**
 * Escapes backslashes ('\') with additional backslashes in a given String, returning a new, escaped String.
 *
 * @param value String to escape.   Cannot be null.
 * @return escaped String.  Never is null.
 *///from  ww  w  .  ja  v  a2s  .  com
public static String escapeBackslashes(String value) {
    StringBuilder buf = new StringBuilder(value);
    for (int looper = 0; looper < buf.length(); looper++) {
        char curr = buf.charAt(looper);
        char next = 0;
        if (looper + 1 < buf.length())
            next = buf.charAt(looper + 1);

        if (curr == '\\') {
            if (next != '\\') { // only if not already escaped
                buf.insert(looper, '\\'); // escape backslash
            }
            looper++; // skip past extra backslash (either the one we added or existing)
        }
    }
    return buf.toString();
}

From source file:com.zuoxiaolong.niubi.job.persistent.hibernate.HibernateNamingStrategy.java

private static String addUnderscores(String name) {
    StringBuilder buf = new StringBuilder(name.replace('.', '_'));
    for (int i = 1; i < buf.length() - 1; i++) {
        if (Character.isLowerCase(buf.charAt(i - 1)) && Character.isUpperCase(buf.charAt(i))
                && Character.isLowerCase(buf.charAt(i + 1))) {
            buf.insert(i++, '_');
        }/*from   ww w . j  ava2s .  com*/
    }
    return buf.toString().toLowerCase(Locale.ROOT);
}

From source file:Main.java

public static String quadKey(int x, int y, final int zoom) {
    final StringBuilder quadKey = new StringBuilder();
    for (int i = zoom; i > 0; i--) {
        char digit = '0';
        final int mask = 1 << (i - 1);
        if ((x & mask) != 0) {
            digit++;/*from   w ww. j  a  va 2s.  c  o  m*/
        }
        if ((y & mask) != 0) {
            digit++;
            digit++;
        }
        quadKey.append(digit);
    }
    if (quadKey.length() > 1) {
        quadKey.insert(0, "0");
    }
    return quadKey.toString();
}

From source file:info.magnolia.vaadin.periscope.result.SupplierUtil.java

/**
 * Highlight (using HTML tags) all occurrences of a query string, ignoring case.
 *
 * @param text Text in which parts should be highlighted
 * @param query Parts to highlight/* w  w  w  .ja  va 2  s.c o m*/
 * @return Highlighted string
 */
public static String highlight(final String text, final String query) {
    if (StringUtils.isBlank(query)) {
        return text;
    }

    final List<Integer> startIndices = allIndicesOf(text, query);
    final List<Integer> endIndices = startIndices.stream().map(i -> i + query.length()).collect(toList());

    // we run back to front to not mess up indices when inserting tags
    Collections.reverse(startIndices);
    Collections.reverse(endIndices);
    Queue<Integer> startQueue = new LinkedList<>(startIndices);
    Queue<Integer> endQueue = new LinkedList<>(endIndices);

    StringBuilder highlighted = new StringBuilder(text);
    while (!startQueue.isEmpty() || !endQueue.isEmpty()) {
        final Integer startCandidate = startQueue.peek();
        final Integer endCandidate = endQueue.peek();

        if (startCandidate != null && (endCandidate == null || startCandidate > endCandidate)) {
            highlighted.insert(startCandidate, "<strong>");
            startQueue.poll();
        } else {
            highlighted.insert(endCandidate, "</strong>");
            endQueue.poll();
        }
    }

    return highlighted.toString();
}

From source file:edu.usu.sdl.openstorefront.common.util.StringProcessor.java

/**
 * Converts a 1.1.1 to a BigDecimal for comparison
 *
 * @param code/*  w  ww  .  ja  v a  2 s  .c  o m*/
 * @return BigDecimal (returns zero on null)
 */
public static BigDecimal archtecureCodeToDecimal(String code) {
    BigDecimal result = BigDecimal.ZERO;
    if (StringUtils.isNotBlank(code)) {
        code = code.replace(".", "");
        if (code.length() > 1) {
            StringBuilder sb = new StringBuilder(code);
            sb.insert(1, ".");
            code = sb.toString();
        }
        result = Convert.toBigDecimal(code, result);
    }
    return result;
}

From source file:de.thischwa.pmcms.tool.PathTool.java

/**
 * Generates the path segment of the hierarchical container, needed e.g. as part of the export path.
 * /*  www .j  ava  2s. c o  m*/
 * @param level
 * @return Hierarchical path segment.
 */
public static String getFSHierarchicalContainerPathSegment(final Level level) {
    if (level == null)
        return "";
    StringBuilder path = new StringBuilder();
    if (!InstanceUtil.isSite(level))
        path.append(level.getName());
    Level tmpContainer = level.getParent();
    while (tmpContainer != null && !InstanceUtil.isSite(tmpContainer)) {
        path.insert(0, tmpContainer.getName().concat(File.separator));
        tmpContainer = tmpContainer.getParent();
    }
    return path.toString();
}

From source file:Dump.java

/**
 *  Converte uma string contendo uma sequncia decimal codificada em BCD
 *  (<em>Binary-Coded Decimal</em> ?). Esta implementao foi obtida a partir da
 *  descrio da codificao BCD encontrada no manual de programao das 
 *  impressoras fiscais Bematech&reg; MP-20 FI II.
 *
 *  <p>Se os valores ASCII dos caracteres de uma string forem <code>0x12, 0x34 e
 *  0x56</code>, ento <code>bcd(s, 2)</code> resultar no valor decimal
 *  <code>1234.56</code>.</p>
 *
 *  @param s a string contendo a sequncia BCD.
 *
 *  @param scale o nmero de casas decimais a serem considerados. Se este
 *         argumento for menor ou igual a zero, ser considerado um valor
 *         inteiro.//from   w  w w  .java  2 s .  c  o m
 *
 *  @return um objeto <code>java.math.BigDecimal</code> contendo o valor
 *          decimal decodificado.
 *
 *  @throws NumberFormatException se a string <code>s</code> no representar
 *          uma sequncia BCD vlida.
 */
public static BigDecimal bcd(final String s, final int scale) {

    StringBuilder hexval = new StringBuilder();

    // converte os valores ASCII da string para hexadecimal
    for (int i = 0; i < s.length(); i++) {
        StringBuilder hex = new StringBuilder(Integer.toString(ascval(s, i), 16));
        if (hex.length() != 2)
            hex.insert(0, "0");
        hexval.append(hex);
    }

    if (scale > 0) {
        if (scale > hexval.length()) {
            // completa com zeros antes da posio de insero do ponto decimal
            int count = scale - hexval.length();
            for (int i = 1; i <= count; i++)
                hexval.insert(0, "0");
        }
        // insere um ponto decimal na posio indicada
        hexval.insert(hexval.length() - scale, ".");
    }

    return new BigDecimal(hexval.toString());

}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

private static void convertNum(long num, Character[] baseChar, Random random, StringBuilder result) {
    if (num <= 0 && result.length() == 0) {
        result.insert(0, baseChar[0]);
    } else if (num > 0) {
        int i = (int) (num % baseChar.length);
        Character ch = random.nextBoolean() ? baseChar[i] : Character.toLowerCase(baseChar[i]);
        result.insert(0, ch);//from  w  w w .  j a  va 2  s  .com
        convertNum(num / baseChar.length, baseChar, random, result);
    }
}

From source file:in.flipbrain.Utils.java

public static String httpGet(String uri, HashMap<String, String> params) {
    StringBuilder query = new StringBuilder();
    for (Map.Entry<String, String> entrySet : params.entrySet()) {
        String key = entrySet.getKey();
        String value = entrySet.getValue();
        query.append(URLEncoder.encode(key)).append("=");
        query.append(URLEncoder.encode(value)).append("&");
    }//from w  w  w  . j  av a 2s  .  com
    if (query.length() > 0) {
        query.insert(0, "?").insert(0, uri);
    }
    String res = null;
    try {
        String fullUrl = query.toString();
        logger.debug("Request URL: " + fullUrl);
        res = Request.Get(fullUrl).execute().returnContent().asString();
        logger.debug("Response: " + res);
    } catch (IOException e) {
        logger.fatal("Failed to process request. ", e);
    }
    return res;
}

From source file:Dump.java

/**
 *  Retorna uma string de tamanho fixo, contendo a representao hexadecimal do valor.
 *
 *  @param value valor inteiro, de base 10, a ser convertido para base 16.
 *
 *  @param length comprimento total desejado. 
 *
 *  @return Representao hexadecimal do valor com o comprimento especificado.
 *          A string resultante ser completada com zeros  esquerda at que o
 *          comprimento total desejado seja atingido.
 *          Se a representao hexadecimal do valor resultar em um comprimento maior 
 *          que o especificado, a string resultante ser formada de asteriscos,
 *          indicando que o comprimento especificado no foi suficiente para o valor. 
 *//*from  w w  w .j  a  v  a 2 s  .co m*/
public static String hex(final int value, final int length) {
    StringBuilder str = new StringBuilder(Integer.toString(value, 16).toUpperCase());
    if (str.length() < length) {
        int falta = (length - str.length());
        for (int i = 1; i <= falta; i++) {
            str.insert(0, "0");
        }
    } else if (str.length() > length) {
        str = new StringBuilder();
        for (int i = 1; i <= length; i++) {
            str.append("*");
        }
    }
    return str.toString();
}