Convert ascii string to native string - Java java.lang

Java examples for java.lang:String Unicode

Description

Convert ascii string to native string

Demo Code


//package com.java2s;

import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        String asciiStr = "java2s.com";
        System.out.println(ascii2native(asciiStr));
    }/*from  w  ww.  j a  va2s  .co m*/

    public static String ascii2native(final String asciiStr) {
        if (asciiStr == null) {
            return null;
        }

        StringBuffer retBuf = new StringBuffer();
        int maxLoop = asciiStr.length();
        for (int i = 0; i < maxLoop; i++) {
            if (asciiStr.charAt(i) == '\\') {
                final int n5 = 5;
                final int n6 = 6;
                final int n16 = 16;
                if (i < maxLoop - n5
                        && (asciiStr.charAt(i + 1) == 'u' || asciiStr
                                .charAt(i + 1) == 'U')) {
                    try {
                        retBuf.append((char) Integer.parseInt(
                                asciiStr.substring(i + 2, i + n6), n16));
                        i += n5;
                    } catch (NumberFormatException e) {
                        retBuf.append(asciiStr.charAt(i));
                    }
                } else {
                    retBuf.append(asciiStr.charAt(i));
                }
            } else {
                retBuf.append(asciiStr.charAt(i));
            }
        }

        return retBuf.toString();
    }

    public static int parseInt(String str, int _default) {
        try {
            return Integer.parseInt(str);
        } catch (Throwable e) {
            return _default;
        }
    }

    public static String toString(Object o) {
        StringBuilder buff = new StringBuilder("{");
        boolean first = true;
        if (o == null) {
            return null;
        } else if (o instanceof Collection<?>) {
            Collection<?> oc = (Collection<?>) o;
            for (Object o1 : oc) {
                if (first == false) {
                    buff.append(",");
                } else {
                    first = false;
                }
                buff.append(toString(o1));
            }
            buff.append("}");
            return buff.toString();
        } else if (o instanceof Object[]) {
            Object[] oa = (Object[]) o;
            for (Object o2 : oa) {
                if (first == false) {
                    buff.append(",");
                } else {
                    first = false;
                }
                buff.append(toString(o2));
            }
            buff.append("}");
            return buff.toString();
        } else {
            return o.toString();
        }
    }
}

Related Tutorials