Java - Write code to replace special characters that affect formatting with non-formatting character sequences.

Requirements

Write code to replace special characters that affect formatting with non-formatting character sequences.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String src = "book\\\t2s.com";
        System.out.println(escape(src));
    }//from  www  .  j a v a  2  s  . c om

    /**
     * replaces special characters that affect formatting with non-formatting
     * character sequences.
     * <ul>
     * <li> \ -> \\
     * <li> &lt;tab&gt; -> \t
     * <li> &lt;CR&gt; -> \r
     * <li> &lt;Newline&gt; -> \n
     * </ul>
     */
    public static String escape(String src) {
        String result = replace(src, "\\", "\\\\");
        result = replace(result, "\t", "\\t");
        result = replace(result, "\r", "\\r");
        result = replace(result, "\n", "\\n");
        result = replace(result, "\"", "\\\"");

        return result;
    }

    /**
     * returns a new string in which one search string is replaced by another.
     */
    public static String replace(String src, String search, String replace) {
        if (src == null)
            return src;
        if (search == null || search.length() == 0)
            throw new IllegalArgumentException(
                    "Search string must not be empty");

        String result = src;
        int ind = 0;
        while ((ind = result.indexOf(search, ind)) >= 0) {
            result = result.substring(0, ind) + replace
                    + result.substring(ind + search.length());
            ind += replace.length();
        }

        return result;
    }

    /**
     * same as String.substring, except that this version handles the case
     * robustly when the index is out of bounds.
     */
    public static String substring(String str, int beginIndex) {
        if (str == null)
            return null;
        if (beginIndex < 0)
            return str;
        if (beginIndex >= str.length())
            return "";

        return str.substring(beginIndex);
    }

    /**
     * same as String.substring, except that this version handles the case
     * robustly when one or both of the indexes is out of bounds.
     */
    public static String substring(String str, int beginIndex, int endIndex) {
        if (str == null)
            return null;
        if (beginIndex > endIndex)
            return "";
        if (beginIndex < 0)
            beginIndex = 0;
        if (endIndex > str.length())
            endIndex = str.length();

        return str.substring(beginIndex, endIndex);
    }
}

Related Exercise