gpt4 book ai didi

java - 使用 Java string.indexOf() 返回不同的子字符串——可能吗?

转载 作者:行者123 更新时间:2023-12-02 08:01:28 25 4
gpt4 key购买 nike

我正在尝试构建一个简单的解释器。基本上,我使用此方法从 ArrayList 中的字符串获取 HashMap 的键。 HashMap 中的字符串可以以 8 种不同的可能性(8 个关键字)开头。目前,我正在使用 string.indexOf("something") 来查找关键字字符串,但当然,一旦我有多个关键字,这就不那么灵活了。

ArrayList 中的所有字符串都可以分解为 COMMAND+(指令)。命令映射到 HashMap 及其类。所以基本上这是一个两步的情况:第一次我需要从字符串中获取第一个单词/标记,然后最好在适当的类中进一步分割/标记字符串的其余部分。

是否可以通过某种方式操作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]);

然后,如果返回指令,则

  1. 如果 parts 的长度为 1,则只需执行 directive.execute()
  2. 否则,用其余部分构成输入并执行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)。

关于java - 使用 Java string.indexOf() 返回不同的子字符串——可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8841394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com