【问题标题】:Tokenize String Disregarding Trailing/Leading Whitespace标记字符串忽略尾随/前导空格
【发布时间】:2017-09-05 17:15:29
【问题描述】:

我必须创建一个 getToken 函数,该函数将一次从输入缓冲区返回一个令牌。我还需要实现一个 isWhiteSpace 函数,如果传递给它的字符是空格(空格、制表符、换行符),则返回 true,如果是 CRLF 或 EOF,则返回 false。

我的问题是当我输入一个字符串时,它只会转到第一个空格字符并停止。如果我以空格开头,它只会打印一个空白字符串。我该如何解决这个问题?

public class Lab1 {

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome to the Tokenizer!");
        while (true) {
            System.out.print("Command: ");
            String s = sc.nextLine();
            String tk = getToken(s);
            if (tk.equals("quit")) {
                break;
            } else {
                System.out.println(tk);
            }
        }
    }

    static String getToken(String w) {
        String b = "";
        for (int i = 0; i < w.length(); i++) {
            char c = w.charAt(i);
            if (!isWhite(c)) {
                b = b + c;
            } else {
                b = b + "";
                break;
            }
        }
        return b;
    }


    static boolean isWhite(char ch) {
        return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n');
    }
}

【问题讨论】:

  • String.trim 有什么问题?
  • 提示:break; 将停止任何周围的 for 循环
  • 在阅读完所有字符之前,您可能不想在此练习中休息一下;...
  • 从您的角度来看,这是一个重要的逻辑问题 - 如果您不明白为什么代码正在做它正在做的事情,那么现在可能与learn to debug 一样好。要弄清楚如何让代码做你想做的事,你可能应该在编写任何代码之前坐下来,在头脑中/在纸上弄清楚。
  • @RC。啊,我明白了!但是当我删除中断时,它最终会组合整个字符串中的标记。我如何将其更改为在单独的行上打印每个令牌的位置?

标签: java string tokenize


【解决方案1】:

如果每行有多个标记,则必须将 getToken 方法重命名为 getTokens 并返回字符串的 ArrayList。 然后,您可以遍历 main 方法上的标记。 这是一个包含一些建议更改的示例代码:

static ArrayList<String> getTokens(String w) {
    ArrayList<String> tokens = new ArrayList<>(0);
    StringBuilder lastWord = new StringBuilder();
    for (int i = 0; i < w.length(); i++) {
        char c = w.charAt(i);
        if (isWhiteSpace(c)) { // rename to isWhiteSpace, it's a more specific name
            tokens.add(lastWord); // if it's a white space add the last word to the list
            lastWord.clear(); // clear the buffer
        } else {
            lastWord.append(c); // append the char to the buffer
        }
    }
    // handle the last word
    if (lastWord.length() > 0) {
      tokens.add(lastWord);
    }
    return tokens;
}

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    相关资源
    最近更新 更多