Java String Java Encode javaEncode(String txt)

Here you can find the source of javaEncode(String txt)

Description

java Encode

License

Apache License

Declaration

public static String javaEncode(String txt) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static String javaEncode(String txt) {
        if ((txt == null) || (txt.length() == 0)) {
            return txt;
        }//from  w  w w  .ja  va2  s  . c  o  m
        txt = replaceEx(txt, "\\", "\\\\");
        txt = replaceEx(txt, "\r\n", "\n");
        txt = replaceEx(txt, "\n", "\\n");
        txt = replaceEx(txt, "\"", "\\\"");
        txt = replaceEx(txt, "'", "\\'");
        return txt;
    }

    public static String replaceEx(String str, String subStr, String reStr) {
        if (str == null) {
            return null;
        }
        if ((subStr == null) || (subStr.equals("")) || (subStr.length() > str.length()) || (reStr == null)) {
            return str;
        }
        StringBuffer sb = new StringBuffer();
        String tmp = str;
        int index = -1;
        while (true) {
            index = tmp.indexOf(subStr);
            if (index < 0) {
                break;
            }
            sb.append(tmp.substring(0, index));
            sb.append(reStr);
            tmp = tmp.substring(index + subStr.length());
        }

        sb.append(tmp);
        return sb.toString();
    }

    public static int indexOf(String str, char strChar) {
        if (isEmpty(str)) {
            return -1;
        }
        return str.indexOf(strChar);
    }

    /**
     * <pre>
     * ExmayStringUtils.indexOf(null, *)          = -1
     * ExmayStringUtils.indexOf(*, null)          = -1
     * ExmayStringUtils.indexOf("", "")           = 0
     * ExmayStringUtils.indexOf("aabaabaa", "a")  = 0
     * ExmayStringUtils.indexOf("aabaabaa", "b")  = 2
     * ExmayStringUtils.indexOf("aabaabaa", "ab") = 1
     * ExmayStringUtils.indexOf("aabaabaa", "")   = 0
     * </pre>
     * 
     * @param str
     * @param searchStr
     * @return
     */
    public static int indexOf(String str, String searchStr) {
        if (str == null || searchStr == null) {
            return -1;
        }
        return str.indexOf(searchStr);
    }

    public static int indexOf(String str, char searchChar, int startPos) {
        if (isEmpty(str)) {
            return -1;
        }
        return str.indexOf(searchChar, startPos);
    }

    public static String subString(String src, int length) {
        if (src == null) {
            return null;
        }
        int i = src.length();
        if (i > length) {
            return src.substring(0, length);
        }
        return src;
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0 || str.equals("") || str.matches("\\s*");
    }
}

Related

  1. javaEncode(String s)
  2. javaEncode(String s)
  3. javaEncode(String txt)