Kotlin 解決Illegal hex characters in escape (%)

解決Illegal hex characters in escape (%) pattern - For input string


class EscapeUnescape {

    /**
     * 編碼
     */
    fun escape(src: String): String? {
        var j: Char
        val buffer = StringBuffer()
        buffer.ensureCapacity(src.length * 6)
        var i: Int = 0
        while (i < src.length) {
            j = src[i]
            if (Character.isDigit(j) || Character.isLowerCase(j)
                || Character.isUpperCase(j)
            ) buffer.append(j) else if (j.code < 256) {
                buffer.append("%")
                if (j.code < 16) buffer.append("0")
                buffer.append(j.code.toString(16))
            } else {
                buffer.append("%u")
                buffer.append(j.code.toString(16))
            }
            i++
        }
        return buffer.toString()
    }

    /**
     * 解碼
     */
    fun unescape(src: String): String? {
        val buffer = StringBuffer()
        buffer.ensureCapacity(src.length)
        var lastPos = 0
        var pos = 0
        var ch: Char
        while (lastPos < src.length) {
            pos = src.indexOf("%", lastPos)
            if (pos == lastPos) {
                if (src[pos + 1] == 'u') {
                    ch = src
                        .substring(pos + 2, pos + 6).toInt(16).toChar()
                    buffer.append(ch)
                    lastPos = pos + 6
                } else {
                    ch = src
                        .substring(pos + 1, pos + 3).toInt(16).toChar()
                    buffer.append(ch)
                    lastPos = pos + 3
                }
            } else {
                lastPos = if (pos == -1) {
                    buffer.append(src.substring(lastPos))
                    src.length
                } else {
                    buffer.append(src.substring(lastPos, pos))
                    pos
                }
            }
        }
        return buffer.toString()
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章