我有这个字符串:
0104120002031190312181225100411040311105000623 07164130140000000272080420120900100101103121120429821320 "
它被编码为TLV,表示标签,长度,值。
01 04 1200
02 03 119
03 12 181221154028
04 03 111
05 00
06 23
07 16 4130140000000272
08 04 2012
09 00
10 01 0
11 03 121
12 04 2982
13 20
现在,我需要某种方式来遍历String并根据标签的长度提取标签的值。 注意:字符串是服务器的响应,每个字段的长度可能会改变。
我已经尝试使用substring
和index
之类的方法,但是它不起作用。
答案 0 :(得分:2)
根据您共享的示例,标签和值的长度似乎分别由2个字符表示。
如果是这样,那么您可以执行以下操作
for(int i = 0; i < input.length(); ){
String tag = input.substring(i,i+2);
String len = input.substring(i+2, i + 4);
String value = input.substring(i+4, Integer.parseInt(len));
i += 4 + Integer.parseInt(len);
}
此外,以上解决方案适用于单个字符串输入。可以做的是将输入字符串拆分为“”,然后对拆分后获得的String数组执行相同的循环处理
答案 1 :(得分:1)
这就是我想出的 我重构了str输入,因为它不是有效的输入
public static void main(String[] args) throws Exception {
String str = "01041200"
+ "0203119"
+ "0312181225100411"
+ "0403111"
+ "0500"
+ "0623 "
+ "07164130140000000272"
+ "08042012"
+ "0900"
+ "10010"
+ "1103121"
+ "12042982"
+ "1300";
Map<String, String> tagValueMap = new HashMap<>();
int tagLength = 2;
int lengthLength = 2;
int index = 0;
while(index < str.length()) {
String tag = str.substring(index, index+tagLength);
int length = Integer.parseInt(str.substring(index+tagLength,index+tagLength+lengthLength));
String value = str.substring(index+tagLength+lengthLength, index+tagLength+lengthLength+length);
tagValueMap.put(tag, value);
index += length +tagLength+lengthLength;
}
System.out.println(tagValueMap);
}
结果是
{11=121, 01=1200, 12=2982, 02=119, 13=, 03=181225100411, 04=111, 05=, 06= , 07=4130140000000272, 08=2012, 09=, 10=0}
希望有帮助
您可以尝试here
答案 2 :(得分:0)
您可以使用扫描仪,将其定界符设置为空字符串,以便逐字符读取输入的字符。读取前两个字符作为标记,后两个字符读取长度,将其中一个解析为int并迭代其数量以获取值:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("");
while (sc.hasNext()) {
String tag = sc.next() + sc.next();
int length = Integer.parseInt(sc.next() + sc.next());
String value = "";
for (int i=0; i<length; i++) {
value+=sc.next();
}
}
您可以try it here。