操纵包含数学操作数的Java字符串。
我正在修改控制信号的代码。我必须转换这种字符串:
String str= "Red 0.20 + 0.60 Green 0.30 + 0.45 + 0.56 Blue 0.25 + 0.50 + 1.0 Yellow 3.0/2.0 ";
到此:
String str1= "RedNet0.8 GreenNet0.75 BlueNet1.75 YellowNet1.5 ";
我可以将Red替换为RedNet,将Green替换为GreenNet等,但可以帮助我继续使用剩余部分。
答案 0 :(得分:0)
解决方案的伪代码:
String[] tokens = input.split(" ");
int index = 0;
while(index < tokens.length) {
String colorName = tokens[index++];
Decimal colorValue = parseNumber(tokens[index++]); // Use some appropriate decimal datatype here
while(true) {
String operator = tokens[index];
if (operator is neither "+", "-" nor any of the other operators) {
break;
}
index++;
switch(tokens[index++]) {
case "+":
colorValue += parseNumber(tokens[index++]);
break;
case "-":
colorValue -= parseNumber(tokens[index++]);
break;
... and so on for all operators ...
}
}
output colorName + "Net" + colorValue + " ";
}
答案 1 :(得分:-1)
StringTokenizer st = new StringTokenizer(msg,"+"); while(st.hasMoreTokens()){ System.out.println(st.nextToken());