Java String Encode encode(final String s)

Here you can find the source of encode(final String s)

Description

encode

License

Apache License

Declaration

public static String encode(final String s)
            throws UnsupportedEncodingException 

Method Source Code

//package com.java2s;
/**/*from w w w.j  a va2s. c  o  m*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class Main {
    public static String encode(final String s)
            throws UnsupportedEncodingException {
        return encode(s, "UTF-8");
    }

    public static String encode(final String s, String encoding)
            throws UnsupportedEncodingException {
        final byte[] rawBytes = s.getBytes(encoding);
        final int len = rawBytes.length;
        final StringBuilder sb = new StringBuilder(len << 1);
        final char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        final byte[] attributeChars = { '!', '#', '$', '&', '+', '-', '.',
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
                'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
                'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
                'v', 'w', 'x', 'y', 'z', '|', '~' };
        for (final byte b : rawBytes) {
            if (Arrays.binarySearch(attributeChars, b) >= 0) {
                sb.append((char) b);
            } else {
                sb.append('%');
                sb.append(digits[0x0f & (b >>> 4)]);
                sb.append(digits[b & 0x0f]);
            }
        }

        return sb.toString();
    }
}

Related

  1. encode(final String s)
  2. encode(final String s, final String encoding)
  3. encode(final String source, final String encoding, BitSet notEncoded)
  4. encode(String data, String encode)
  5. encode(String encoding, String string)