我正在为正在制作的torrent下载系统实现bencoding系统。

对字符串进行明码编码非常容易,您可以选择一个字符串,例如“ hello”,然后通过编写字符串长度+':'字符,再加上字符串本身来对它进行编码。编码为“ hello”的将是“ 5:hello”

目前,我正在使用此代码。

public BencodeString(String string) {
    this.string = string;
}

public static BencodeString parseBencodeString(String string) {
    byte[] bytes = string.getBytes();
    int position = 0;
    int size = 0;
    StringBuilder sb = new StringBuilder();
    while (bytes[position] >= '0' && bytes[position] <= '9') {
        sb.append((char) bytes[position]);
        position++;
    }
    if (bytes[position] != ':')
        return null;

    size = Integer.parseInt(sb.toString());
    System.out.println(size);
    if (size <= 0)
        return null;
    return new BencodeString(string.substring(position + 1, size + position
            + 1));
}


它可以工作,但是我感觉可以做得更好。做这个的最好方式是什么?

注意:字符串可以是任意大小(因此,字符串前应多一位数字)

已经解决了,感谢大家在这里回答:)

最佳答案

string.substring(string.indexOf(':'))

这就是您需要做的。您已经知道数据的大小,因为所有内容都放在String中。

关于java - [Java]编码:解码字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12443171/

10-10 00:56
查看更多