Escapes the given text such that it can be safely embedded in a string literal in Java source code. - Java java.lang

Java examples for java.lang:String Escape

Introduction

The following code shows how to Escapes the given text such that it can be safely embedded in a string literal in Java source code.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String text = "java2s.com";
        System.out.println(escapeToJavaString(text));
    }/*ww  w.j a  v a 2s .c  o  m*/

    /**
     * Escapes the given text such that it can be safely embedded in a string literal
     * in Java source code.
     * 
     * @param text the text to escape
     * 
     * @return the escaped text
     */
    public static String escapeToJavaString(String text) {
        if (text == null) {
            return null;
        }
        String result = text.replaceAll("\\\\", "\\\\\\\\")
                .replaceAll("\"", "\\\\\"").replace("\b", "\\b")
                .replace("\f", "\\f").replace("\n", "\\n")
                .replace("\r", "\\r").replace("\t", "\\t");
        StringBuilder complete = new StringBuilder();
        for (int i = 0; i < result.length(); i++) {
            int codePointI = result.codePointAt(i);
            if (codePointI >= 32 && codePointI <= 127) {
                complete.append(Character.toChars(codePointI));
            } else {
                // use Unicode representation
                complete.append("\\u");
                String hex = Integer.toHexString(codePointI);
                complete.append(getRepeatingString(4 - hex.length(), '0'));
                complete.append(hex);
            }
        }
        return complete.toString();
    }

    public static String getRepeatingString(int count, char character) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < count; i++) {
            result.append(character);
        }
        return result.toString();
    }
}

Related Tutorials