string tokenizer in Java

后端 未结 7 1222
耶瑟儿~
耶瑟儿~ 2020-12-02 20:58

I have a text file which contains data seperated by \'|\'. I need to get each field(seperated by \'|\') and process it. The text file can be shown as below :

相关标签:
7条回答
  • 2020-12-02 21:48

    Use the returnDelims flag and check two subsequent occurrences of the delimiter:

    String str = "ABC|DEF||FGHT";
    String delim = "|";
    StringTokenizer tok = new StringTokenizer(str, delim, true);
    
    boolean expectDelim = false;
    while (tok.hasMoreTokens()) {
        String token = tok.nextToken();
        if (delim.equals(token)) {
            if (expectDelim) {
                expectDelim = false;
                continue;
            } else {
                // unexpected delim means empty token
                token = null;
            }
        }
    
        System.out.println(token);
        expectDelim = true;
    }
    

    this prints

    ABC
    DEF
    null
    FGHT
    

    The API isn't pretty and therefore considered legacy (i.e. "almost obsolete"). Use it only with where pattern matching is too expensive (which should only be the case for extremely long strings) or where an API expects an Enumeration.

    In case you switch to String.split(String), make sure to quote the delimiter. Either manually ("\\|") or automatically using string.split(Pattern.quote(delim));

    0 讨论(0)
提交回复
热议问题