阿里Java学习路线:阶段 1:Java语言基础-Java面向对象编程:第11章: String类常用方法:课时55:字符串拆分

在字符串处理的时候还提供一种字符串拆分的处理方法,字符串的拆分操作主要是可以根据一个指定的字符串或者是一些表达式实现字符串的拆分,并且拆分完成的数据将以字符串数组的形式返回。

No. 方法名称 类型 描述
01 public String[] split​(String regex) 普通 按照指定的字符串全部拆分
02 public String[] split​(String regex,int limit) 普通 按照指定的字符串拆分为指定个数,后面不拆了

范例:观察字符串拆分处理

public class StringDemo {
	public static void main(String args[]) {
		String str = "hello world hello mldn" ;
		String result [] = str.split(" ") ; // 空格拆分
		for (int x = 0 ; x < result.length ; x ++ ) {
			System.out.println(result[x]) ; 
		}
	}
}

除了可以全部拆分之外,也可以拆分为指定的个数
范例:拆分指定个数

public class StringDemo {
	public static void main(String args[]) {
		String str = "hello world hello mldn" ;
		String result [] = str.split(" ",2) ; // 空格拆分
		for (int x = 0 ; x < result.length ; x ++ ) {
			System.out.println(result[x]) ; 
		}
	}
}

但是在进行拆分的时候有可能会遇见拆不了的情况,这个时候最简单的理解就是使用“\”进行转义。

public class StringDemo {
	public static void main(String args[]) {
		String str = "192.168.1.2" ;
		String result [] = str.split("\\.") ; // 转义处理
		for (int x = 0 ; x < result.length ; x ++ ) {
			System.out.println(result[x]) ; 
		}
	}
}

对于拆分与替换的更多操作后续才会进行说明。

你可能感兴趣的:(java,学习,阿里Java学习路线)