子字符串和 Vector.add 问题

Issue with substring and Vector.add

代码:

private static Vector<String> storage = new Vector<>();

//Message -> Vector
private static void convertToVector(String string) {
    String msg = string;

    int tempInt = 0;

    while (msg.length() > 1) {
        int run = 0;

        if (msg.indexOf('[') >= 0 && msg.indexOf(']') > 0 && msg.indexOf(':') >= 0) {
            storage.add(msg.substring(msg.indexOf('[')+1, msg.indexOf(':')));
        }

        if (msg.indexOf(':') > 0 && msg.indexOf(']') > 0) {
            tempInt = msg.indexOf("][#");
            if (tempInt < 1)
                tempInt = msg.length()-1;   
            storage.add(msg.substring(msg.indexOf(':')+1, tempInt));
        }

        if (msg.length() > tempInt) {
            msg = msg.substring(tempInt+1);
            run = 1;
        }

        if (msg.length() == tempInt || run == 0)
            msg = "";
    }

    for (int i = 0; i < storage.size(); i++) {
                System.out.println(storage.get(i));
    }
}


案例 1 msg = [#userInfo#:xyz] <-- working

    #userInfo#
    xyz

案例 2 msg = [#userInfo#:xyz][#userInfo#:xy] <-- 不工作?

    #userInfo#
    xyz

案例 3 消息 = [#userInfo#:xyz][#userInfo#:xy][#userInfo#:gfdgfd] <-- working

    #userInfo#
    xyz
    #userInfo#
    xy
    #userInfo#
    gfdgfd

谁能解释为什么 case2 不起作用,只有当最后一个用户名等于前一个减去最后一个字母时才会发生。

我怀疑您想将上次支票更改为:

        if (msg.length() > tempInt) {
            msg = msg.substring(tempInt + 1);
        } else {
            msg = "";
        }

并删除 运行 变量。

照原样,在情况 2 中,在消息已经被修改以删除初始匹配项之后,根据 tempInt 检查消息长度,并且巧合的是还剩下 tempInt 字符。

我认为你只是想在匹配失败或到达字符串末尾时停止,所以 "else" 应该没问题,除非我遗漏了什么。

我不知道你为什么会这样:

if (msg.length() == tempInt || run == 0) msg = "";

在第二种情况下,这是正确的并且您正在退出循环,因为您的 while 条件是 msg.length() > 1.

注释掉该行,看看它是否提供了您想要的输出。