Java Char Array to String charArrayToString(char[] input, int offset, int length, int maxChars)

Here you can find the source of charArrayToString(char[] input, int offset, int length, int maxChars)

Description

Converts a subset of a character array to a String representation.

License

Open Source License

Parameter

Parameter Description
input the character array to convert
offset offset of the first character in the array subset to convert.
length the number of characters in the array subset.
maxChars imposes a maximum character length limit on the subset. If length is greater than maxChars, the subset will be truncated.

Return

the String representation of the character array subset.

Declaration

public static String charArrayToString(char[] input, int offset, int length, int maxChars) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from www . jav  a 2s .c o m*/
     * Converts a subset of a character array to a String representation.
     * Non-printing characters (not in the range <code>32-126</code>) are displayed as hex values 
     * (eg. <code>x1F</code>)
     * @param input the character array to convert
     * @param offset offset of the first character in the array subset to convert.
     * @param length the number of characters in the array subset.
     * @param maxChars imposes a maximum character length limit on the subset.
     * If length is greater than maxChars, the subset will be truncated.
     * @return the String representation of the character array subset.
     */
    public static String charArrayToString(char[] input, int offset, int length, int maxChars) {
        StringBuffer buf = new StringBuffer();
        boolean inHex = false;
        if (length < 0) {
            length = input.length;
        } else {
            length = offset + length;
        }
        if (length > input.length) {
            length = input.length;
        }
        for (int i = offset; i < length; i++) {
            char c = input[i];
            if (c < 32 || c > 126) {
                if (!inHex) {
                    buf.append(String.format("x%02X", (int) c));
                    inHex = true;
                } else {
                    buf.append(String.format(".%02X", (int) c));
                }
            } else {
                inHex = false;
                buf.append(c);
            }
            if (buf.length() > maxChars) {
                break;
            }
        }
        return buf.toString();
    }
}

Related

  1. charArrayToCharSequence( final char[] charArray)
  2. charArrayToString(char[] ch, String separator)
  3. charArrayToString(Character[] chars)
  4. charArrayToXml(char[] input, int offset, int length)
  5. charsToString(char[] chars)
  6. charsToString(char[] chars)