Java tutorial
//package com.java2s; /** * Copyright (c) 2013, 2014 Denis Nikiforov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Denis Nikiforov - initial API and implementation */ public class Main { /** * 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(); } }