【发布时间】:2012-09-15 23:09:21
【问题描述】:
我正在为我正在制作的种子下载系统实现一个编码系统。
对字符串进行编码非常简单,您可以获取一个字符串,例如“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));
}
它有效,但我觉得它可以做得更好。做这个的最好方式是什么?
注意:字符串可以是任意大小(因此字符串前多于一位)
已经解决了,谢谢大家在这里回复:)
【问题讨论】:
-
这听起来像是一个问题,在codereview.stackexchange.com 上会得到更好的回答
-
您可以在扫描长度末尾时手动解析长度,这样可以避免构建一个您无论如何都要解析的新字符串
-
你需要的是 String.indexOf 函数来找到:
-
@Edc String$indexOf 可以,谢谢
标签: java regex encoding bittorrent