簡體   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