我正在尝试构建一个简单的解释器。基本上,我使用这个方法从ArrayList
中的字符串中获得HashMap
的密钥。HashMap
中的字符串可以从8种不同的可能性(8个关键字)开始。目前,我使用string.indexOf("something")
来查找关键字字符串,但当然,一旦我有多个关键字,这就一点也不灵活了。
ArrayList
中的所有字符串都可以分解为COMMAND+(INSTRUCTIONS)。COMMAND映射到HashMap
及其类。因此,基本上这是一个两步的情况:第一次通过时,我需要从String中获得第一个单词/标记,然后最好在适当的类中进一步拆分/标记字符串的其余部分。
是否有string.indexOf()
可以以某种方式被操纵以返回多个子字符串的索引?还是我必须在其他地方寻找其他方法?请告知。
代码如下:
public void parseCommands() {
List<String> myString = new ArrayList<String>();
myString.add(new String("# A TPL HELLO WORLD PROGRAM"));
myString.add(new String("# xxx"));
myString.add(new String("STRING myString"));
//myString.add(new String("LET myString= "HELLO WORLD""));
//myString.add(new String("PRINTLN myString"));
myString.add(new String("PRINTLN HELLO WORLD"));
myString.add(new String("END"));
System.out.println();
for (String listString : myString)//iterate across arraylist
{
if (listString.startsWith("#", 0))//ignore comments starting with #
{
continue;
}
int firstToken = listString.indexOf("END");
String command = listString;
Directive directive = commandHash.get(command);
if (directive != null) {
directive.execute(listString);
} else {
System.out.println("No mapped command given");
}
}
}
看起来AL中的每个字符串可能只是一个命令,也可能只是命令和命令的输入。
我认为你可以在这里使用split
方法:
String[] parts = listString.split(" ");
如果parts
的大小是1,则意味着它只是一个命令,否则parts[0]
是一个命令而其余的是该命令的输入。
使用它进行查找:
Directive directive = commandHash.get(parts[0]);
然后,如果返回Directive
,则
- 如果
parts
的长度是1,那么只做directive.execute()
- 否则,与其余的
parts
一起形成输入,然后执行directive.execute(input)
如果不是这样的话,也许我没有明白你想说的话。
另外,请参阅String
,它提供了您可以在这里使用的所有方法。
更新:
public interface Directive {
void execute(String input);
}
public class EndDirective implements Directive {
@Override
public void execute(String input) {
// input will be neglected here
// just do whatever you supposed to do
}
}
public class PrintlnDirective implements Directive {
@Override
public void execute(String input) {
// input will be used here
// you might want to check if the input is null here
// and write the code accordingly
System.out.println(input);
}
}
这样,当您没有任何输入时,您可以执行directive.execute(null);
,因为您相应的Directive
要么忽略输入,要么使用它(如果他们在期望一些输入时收到null,也可能处理null)。
简单的答案是否定的。您可能想要使用String.split()、StreamTokenizer或StringTokenizer。