(4)StringTokenizer分隔字符串之处理连续的分隔符

import java.util.StringTokenizer;

//使用StringTokenizer类,包括返回分隔符
public class StrTokDemo002 {
	public final static int MAXFIELDS=5;
	public final static String DELIM="|";
	//处理一个字符串,返回一个由各域组成的数组
	public static String[] process(String line){
		
		String[] results=new String[MAXFIELDS];
		
		//除非你要求StringTokenizer类,否则它会丢弃多个null标记
		StringTokenizer st=new StringTokenizer(line,DELIM,true);
		int i=0;
		//获得每个token
		while(st.hasMoreTokens()){
			String s=st.nextToken();
			if(s.equals(DELIM)){
				if(i++>=MAXFIELDS)
					//参见示例StrTokDemo
					throw new IllegalArgumentException("Input line "+line+" has too many fields");
				continue;
			}
			results[i]=s;
		}
		return results;
	}
	
	public static void printResults(String input,String[] outputs){
		System.out.println("Input:"+input);
		for(int i=0;i<outputs.length;i++){
			System.out.println("Output "+i+" was:"+outputs[i]);
		}
	}
	
	public static void main(String[] args) {
		printResults("A|B|C|D",process("A|B|C|D"));
		printResults("A||C|D",process("A||C|D"));
		printResults("A|||D|E",process("A|||D|E"));
	}
	
	
}

你可能感兴趣的:((4)StringTokenizer分隔字符串之处理连续的分隔符)