Java StringTokenizer, empty null tokens

前端 未结 5 1568
有刺的猬
有刺的猬 2021-01-04 14:32

I am trying to split a string into 29 tokens..... stringtokenizer won\'t return null tokens. I tried string.split, but I believe I am doing something wrong:

         


        
5条回答
  •  攒了一身酷
    2021-01-04 14:49

    If you want empty tokens to be retained string.split() won't work satisfactorily. StringTokenizer will also not work. I have come with following method, which might be helpful for you:

    public static String[] splitTotokens(String line, String delim){
        String s = line;
        int i = 0;
    
        while (s.contains(delim)) {
            s = s.substring(s.indexOf(delim) + delim.length());
            i++;
        }
        String token = null;
        String remainder = null;
        String[] tokens = new String[i];
    
        for (int j = 0; j < i; j++) {
            token = line.substring(0, line.indexOf(delim));
            // System.out.print("#" + token + "#");
            tokens[j] = token;
            remainder = line.substring(line.indexOf(delim) + delim.length());
            //System.out.println("#" + remainder + "#");
    
            line = remainder;
        }
        return tokens;
    }
    

提交回复
热议问题