簡體   English   中英

JAVA中的代碼上可能有哪些隱藏字符?

[英]What hidden charactere could be on my code in JAVA?

我正在做一個詞法分析器,並且遇到了一些問題。 從源代碼中讀取所有字符后,將它們放在字符串中,然后逐個字符地讀取並進行適當的操作。 最后,這將生成一個包含語言標記,空格,換行符和...一個我無法識別且需要清除的可惡字符的列表。

for (int i = 0; i < tokenList.size(); i++) {
    // Remove Espacos
    if (tokenList.get(i).getLexema().equals(" ")) {
        tokenList.remove(i);
    }
    // Remove Strings Vazias
    else if (tokenList.get(i).getLexema().length() == 0) {
        print("ada");
        tokenList.remove(i);
    }
    // Remove Tabulação
    else if (tokenList.get(i).getLexema().equals("\t")) {
        tokenList.remove(i);
    }
    // Remove Quebras de Linha
    else if (tokenList.get(i).getLexema().equals("\n")) {
        print("ASD");
        tokenList.remove(i);
    }
}

從以下條目:

int a;
char n;

經過所有分析和清理,我得到以下結果:

00 - Lex: int
01 - Lex: a
02 - Lex: ;
03 - Lex: 
04 - Lex: char
05 - Lex: n
06 - Lex: ;

有一個空白空間,我不知道如何刪除它。

解:

好吧,那些家伙真是不可思議,我可以解決我的問題。 該解決方案使用了一些更好的編碼策略:

for (int i = 0; i < tokenList.size(); i++) {
    String lexema = tokenList.get(i).getLexema();

    switch (lexema) {
        case "":
            tokenList.remove(i);
            i = i - 1;
            break;
        // Remove Espacos
        case " ":
            tokenList.remove(i);
            i = i - 1;
            break;
        // Remove Tabulações
        case "\t":
            tokenList.remove(i);
            i = i - 1;
            break;
        // Remove Quebras de Linha
        case "\n":
            tokenList.remove(i);
            i = i - 1; // DEIXAR SEM O BREAK
            break;
        // Remove Caractere Estranho
        case "\r":
            tokenList.remove(i);
            i = i - 1;
            break;
        default:
            break;
        }
}

另一種簡便的解決方案是使用Character.isWhitespace() 因此,您的代碼可能很簡單:

for (int i = 0; i < tokenList.size(); i++) {
    String lexema = tokenList.get(i).getLexema();
    char c = lexema.charAt(0);

    if (Character.isWhitespace(c)) {
        tokenList.remove(i);
        i = i - 1;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM