Skip to content


Reemplazar caracteres no ASCII de un String en Java

Rutina simple y útil:

Se proporciona con una clase de prueba:

package pruebas;
/**
 *
 * @author diego
 */
public class ReplaceNonAscii {
    public static void main(String[] args) {
        byte[] bytes =
                    {
        (byte)0x32, (byte)0x30, (byte)0x32, (byte)0x32,
        (byte)0x35, (byte)0x36, (byte)0x32, (byte)0x39,
        (byte)0x50, (byte)0x41, (byte)0xa5, (byte)0x43,
        (byte)0x48, (byte)0x4f, (byte)0x20, (byte)0x50,
        (byte)0x41, (byte)0x4e, (byte)0x41, (byte)0x4c};

        String str = new String(bytes);
        System.out.println("RPTA=[" + cleanNonAscii(str) + "]");
    }
    public static String cleanNonAscii(String str) {
        StringBuffer rpta = new StringBuffer(str.length());
        for (int z = 0; z < str.length(); z++) {
            char c = str.charAt(z);
            if (c < 0x20 || c > 0x7e) {
                rpta.append('.');
            } else {
                rpta.append(c);
            }
        }
        return rpta.toString();
    }
}
Share

Posted in Java.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

You must be logged in to post a comment.