Java中split、substring、stringtokenizer各自的用法

import java.util.StringTokenizer;

public class CutString {

	public static void main(String[] args) {
		String str="abcde";
		String str2="I am your father";
		String str3="192.168.0.1";
		
		//截取掉str从首字母开始长度为beginIndex的字符串,然后将剩余字符串赋值给str
		System.out.println("我是被substring(beginIndex)分割的:"+str.substring(2));
		
		//截取str中从beginIndex开始至endIndex结束时(不包括索引为endIndex的字母)的字符串,并将其赋值给str
		System.out.println("我是被substring(beginIndex,endIndex)分割的:"+str.substring(2,4));
		
		//按指定 的分隔符进行分割,然后返回字符串数组
		String[] strArray=str.split("c");
		for(String a:strArray) {
			System.out.println("我是被split(\"c\")分割的: "+a);
		}
		
		//限制最多只能分割成两个数组元素,limit控制数组元素个数
		String[] strArray2=str2.split(" ", 2);
		for(String a:strArray2) {
			System.out.println("我是被split(\" \",limit)分割的: "+a);
		}
		
		//特殊分割符要在前面加上\\
		String[] strArray3=str3.split("\\.");
		for(String a:strArray3) {
			System.out.println("我是被split(\".\")分割的: "+a);
		}
		
		//StringTokenizer默认分隔符\t\n\r\f
		StringTokenizer st1=new StringTokenizer(str2);
		while(st1.hasMoreTokens()) {
			System.out.println("我是被stringtokenizer分割的: "+st1.nextToken());
		}
		
		StringTokenizer st2=new StringTokenizer(str3,".",true);
		while(st2.hasMoreTokens()) {
			System.out.println("我是被stringtokenizer(str3,\".\",true)分割的: "+st2.nextToken());
		}
		
		//通过nextToken(String delim)可以使用新定义的分隔符
		StringTokenizer st3=new StringTokenizer(str3,".",true);
		while(st3.hasMoreTokens()) {
			System.out.println("我是被stringtokenizer的nextToken方法重新定义分割的: "+st3.nextToken("1"));
		}
	}
}

猜你喜欢

转载自blog.csdn.net/wulibabywenyu/article/details/79631242
0条评论
添加一条新回复