繁体   English   中英

检查两个双引号之间的ArrayList中的元素

[英]Checking element in ArrayList between two double quotes

我正在用Java编写用于自定义语言的原始版本的编程语言阅读器,我想找到一种最简单的方法来打印位于双引号两个元素之间的ArrayList中的元素内容。 这是源代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;

public class PrimitiveCompiler {

    public static ArrayList<String> toks = new ArrayList<String>();

    public static void main(String[] args) throws FileNotFoundException {
        String content = readFile("C:\\program.txt");

        tokenize(content);
    }

    public static String readFile(String filePath) throws FileNotFoundException {
        File f = new File(filePath);
        Scanner input = new Scanner(f);

        StringBuilder b = new StringBuilder();

        while (input.hasNextLine()) {
            b.append(input.nextLine());
        }

        input.close();

        return b.toString();
    }

    public static ArrayList<String> tokenize(String fContent) {
        int i = 0;
        String tok = "";

        String contents = fContent.replaceAll(" ", "").replaceAll("\n", "").replaceAll("\t", "");

        for(int a = 0; a <= contents.length() - 1; a++) {
            tok += contents.charAt(a);
            i = a;

            if(tokenFinderEquals(tok, "WRITE")) {
                toks.add("WRITE");
                tok = "";
            }
        }

        System.out.println(toks);

        return null;

        }

    public static boolean tokenFinderEquals(String s1, String s2) {
        if(s1.equalsIgnoreCase(s2)) {
            return true;
        }

        return false;
    }
}

现在,文本文件的内容只是WRITE ,它可以成功找到它并将其添加到ArrayList 我想做的是计算双引号,并在ArrayList中找到两个双引号以打印出它们之间的每个元素。 是摆设还是其他更简单的方法? 提前致谢!

您需要某种状态来跟踪您是否在报价单内。 例如:

boolean inQuote = false;
for (int a = 0; a <= contents.length() - 1; a++) {
  char c = contents.charAt(a);
  if (c == '"') {
    // Found a quote character. Are we at the beginning or the end?
    if (!inQuote) {
      // Start of a quoted string.
      inQuote = true;
    } else {
      // End of a quoted string.
      inQuote = false;
      toks.add(tok);
      tok = "";
    }
    // Either way, we don't add the quote char to `tok`.
  } else {
    tok += c;
    if (!inQuote && tokenFinderEquals(tok, "WRITE") {
      // Only look for "WRITE" when outside of a quoted string.
      toks.add(tok);
      tok = "";
    }
  }
}

但是,随着添加更多案例,使用这样的简单循环可能会变得越来越困难。 您可能需要研究编写递归下降解析器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM