如何在java中为UTF8字符串做子串?

Wae*_*ael 6 java oracle substring

假设我有以下字符串:RückrufinsAusland我需要将其插入到最大大小为10的数据库中.我在java中执行了一个正常的子字符串,它提取了这个字符串Rückruf,其中包含10个字符.当它试图插入此列时,我得到以下oracle错误:

java.sql.SQLException:ORA-12899:值太大而不能列"WAEL"."TESTTBL"."DESC"(实际:11,最大值:10)原因是数据库有一个AL32UTF8字符集,因此ü将采取2个字符.

我需要在java中编写一个执行此子字符串的函数,但考虑到ü需要2个字节,因此在这种情况下返回的子字符串应该是Rückrufi(9个字符).有什么建议?

Gio*_*nni 2

如果你想在 Java 中修剪数据,你必须编写一个函数,使用所使用的 db 字符集修剪字符串,如下测试用例:

\n\n
package test;\n\nimport java.io.UnsupportedEncodingException;\n\npublic class TrimField {\n\n    public static void main(String[] args) {\n        //UTF-8 is the db charset\n        System.out.println(trim("R\xc3\xbcckruf ins Ausland",10,"UTF-8"));\n        System.out.println(trim("R\xc3\xbc\xc3\xbcckruf ins Ausland",10,"UTF-8"));\n    }\n\n    public static String trim(String value, int numBytes, String charset) {\n        do {\n            byte[] valueInBytes = null;\n            try {\n                valueInBytes = value.getBytes(charset);\n            } catch (UnsupportedEncodingException e) {\n                throw new RuntimeException(e.getMessage(), e);\n            }\n            if (valueInBytes.length > numBytes) {\n                value = value.substring(0, value.length() - 1);\n            } else {\n                return value;\n            }\n        } while (value.length() > 0);\n        return "";\n\n    }\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n