美文网首页
Kotlin 解决Illegal hex characters

Kotlin 解决Illegal hex characters

作者: 爱学习的蹭蹭 | 来源:发表于2021-10-06 21:29 被阅读0次

解决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()
    }
}

相关文章

网友评论

      本文标题:Kotlin 解决Illegal hex characters

      本文链接:https://www.haomeiwen.com/subject/xaoonltx.html