【发布时间】:2019-01-22 05:10:18
【问题描述】:
我有一个输入字符串,如果该字符串包含 elseif,那么我需要将该字符串拆分为多行,如预期输出所示。
if ((tag eq 200)) then
set weight 200
elseif ((tag eq 300)) then
set weight 300
elseif ((tag eq 400)) then
set weight 400
elseif ((tag eq 250)) then
set weight 0
else pass endif
我已经实现了下面的代码来拆分,如上所示。它给出了预期的结果。但是下面的代码不是优化的。有人可以建议对以下代码进行任何优化。
public class Test {
public static void main(String[] args) {
String str = "if ((tag eq 200)) then set weight 200 elseif ((tag eq 300)) then set weight 300 elseif ((tag eq 400)) then set weight 400 elseif ((tag eq 250)) then set weight 0 else pass endif";
System.out.println(str);
if(str.contains("elseif")) {
int lastIndex = str.lastIndexOf("then");
String subString = str.substring(0, lastIndex + 4);
splitTextByThen(subString);
String subString1 = str.substring(lastIndex+4 , str.length());
splitTextByElseIfOrElse(subString1);
}
}
public static void splitTextByThen(String input) {
String[] arr = input.split("then");
for (int i = 0; i < arr.length; i++) {
splitTextByElseIfOrElse(arr[i] + "then");
}
}
public static void splitTextByElseIfOrElse(String input) {
ArrayList<String> al = new ArrayList<>();
if(input.contains("elseif")) {
String[] arr = input.split("elseif");
al.add(arr[0]);
al.add("elseif " +arr[1]);
}else if (input.contains("else")) {
String[] arr = input.split("else");
al.add(arr[0]);
al.add("else " +arr[1]);
}
else {
al.add(input);
}
for (String string : al) {
System.out.println(string);
}
}
}
【问题讨论】:
-
碰巧你正在实现一个文本解析器?