有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

按代码点索引的字符串Java子字符串(将代理代码单元对视为单个代码点)

我有一个小的演示应用程序,展示了当使用需要代理项对的unicode代码点(即不能用2字节表示)时,Java的子字符串实现的问题。我想知道我的解决方案是否有效,或者我是否遗漏了什么。我曾考虑过在codereview上发帖,但这更多地与Java的字符串实现有关,而不是与我的简单代码本身有关

public class SubstringTest {
    public static void main(String[] args) {

        String stringWithPlus2ByteCodePoints = "👦👩👪👫";

        String substring1 = stringWithPlus2ByteCodePoints.substring(0, 1);
        String substring2 = stringWithPlus2ByteCodePoints.substring(0, 2);
        String substring3 = stringWithPlus2ByteCodePoints.substring(1, 3);

        System.out.println(stringWithPlus2ByteCodePoints);
        System.out.println("invalid sub" + substring1);
        System.out.println("invalid sub" + substring2);
        System.out.println("invalid sub" + substring3);

        String realSub1 = getRealSubstring(stringWithPlus2ByteCodePoints, 0, 1);
        String realSub2 = getRealSubstring(stringWithPlus2ByteCodePoints, 0, 2);
        String realSub3 = getRealSubstring(stringWithPlus2ByteCodePoints, 1, 3);
        System.out.println("real sub:"  + realSub1);
        System.out.println("real sub:"  + realSub2);
        System.out.println("real sub:"  + realSub3);
    }

    private static String getRealSubstring(String string, int beginIndex, int endIndex) {
        if (string == null)
            throw new IllegalArgumentException("String should not be null");
        int length = string.length();
        if (endIndex < 0 || beginIndex > endIndex || beginIndex > length || endIndex > length)
            throw new IllegalArgumentException("Invalid indices");
        int realBeginIndex = string.offsetByCodePoints(0, beginIndex);
        int realEndIndex = string.offsetByCodePoints(0, endIndex);
        return string.substring(realBeginIndex, realEndIndex);
    }

}

输出:

👦👩👪👫
invalid sub: ?
invalid sub: 👦
invalid sub: ??
real sub: 👦
real sub: 👦👩
real sub: 👩👪

我能否依靠我的子字符串实现始终给出所需的子字符串,从而避免Java在使用chars作为其子字符串方法时遇到的问题


共 (0) 个答案