Checks a given String for '\' char and replaces '\' with '\\' Also replaces the \r\n to \\r\\n . - Java java.lang

Java examples for java.lang:String New Line

Description

Checks a given String for '\' char and replaces '\' with '\\' Also replaces the \r\n to \\r\\n .

Demo Code

// All Rights Reserved.
import java.util.*;
import java.io.*;
import java.sql.*;
import java.lang.reflect.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.JspWriter;
import java.util.zip.*;
import java.text.*;

public class Main{
    public static void main(String[] argv) throws Exception{
        String str = "java2s.com";
        System.out.println(escapeSlash(str));
    }//  w  w w  . j a  v a  2s.  c om
    /**
     * Checks a given String for '\' char and replaces '\' with '\\' Also
     * replaces the \r\n to \\r\\n .
     *
     * @param str String in which the escape to happen.
     *
     * @return String with escape char embedded if needed.
     */
    public static String escapeSlash(String str) {
        // Get the String in array of chars
        char[] charArray = str.toCharArray();

        // Make a String Buffer object
        StringBuffer sb = new StringBuffer();

        // Append the chars in the StringBuffer object and if
        // the char is '\' then append another '\' char
        for (int i = 0; i < charArray.length; i++) {
            // Replace \ with \\
            if (charArray[i] == '\\') {
                sb.append('\\');
            }

            // Taking Care of the NEW LINE Character.
            // On Windows the new line made of two chars \r\n
            // (System.getProperty("line.separator")). If we
            // do not do following, then while the string is
            // getting loaded in the TextArea via JavaScript
            // it will give "Unterminated string constant"
            // error. So replace \r with \\r and \n with \\n
            // ie \r\n to \\r\\n
            if (charArray[i] == '\r') {
                sb.append('\\');
                sb.append('r');
                continue;
            }
            if (charArray[i] == '\n') {
                sb.append('\\');
                sb.append('n');
                continue;
            }

            // Append the char
            sb.append(charArray[i]);
        }

        // Convert the StringBuffer to String
        return sb.toString();
    }
}

Related Tutorials