我需要一种从变量字符串中提取许多不同值/字符串的有效方法
double A = 0;
int B = 0;
double C = 0;
String D = null;
int E = 0;
double F = 0;
String D = null;
[...]
string1 = "A=1.00;B=2;C=1.00;D=TEST;E=24;F=0.00;D=FS[...]"
string2 = "A=3.00;B=3;D=SOMESTRING;E=24;F=0.00;[..]"
string3 ="A=2.64;B=4;C=1.00;D=SOMEOTHERSTRING;E=24;D=FS[...]"
有没有高效,快速,可能优雅的方式来做到这一点?
我已经尝试使用.split(“;”),但如果字符串是变量,我有问题!
感谢您对此主题的任何想法/帮助!
答案 0 :(得分:0)
如果您可以使用字符串参数的setter方法,则可以使用反射
String[] split1 = string1.split(";");
for (int i=0;i<split1.length;i++) {
String[] insideSplit = split1[i].split("=");
java.lang.reflect.Method method;
try {
method = this.getClass().getMethod("set" + insideSplit[0], String.class);
method.invoke(this, insideSplit[1]);
} catch (Exception e) {
// ...
}
}
然后,在你的setter方法中,你可以相应地处理字符串值(将它们转换为double或int或任何你想要的)
答案 1 :(得分:0)
string1 = "A=1.00;B=2;C=1.00;D=TEST;E=24;F=0.00;D=FS[...]"
Matcher matcher = Pattern.compile("[A][=]([0-9]+\\.[0-9]+)").matcher(info);
if (matcher.find()) {
A = Double.parseDouble(matcher.group(1));
}