split()
方法根据给定的分隔符,将一个String拆分为多个String。返回的对象是拆分后的String的数组。
我们还可以通过设置limit
参数限制分隔的数量。如果传0,表示不做任何限制。
2个重载方法
public String[] split(String regex, int limit)
public String[] split(String regex)
例子
@Test
public void whenSplit_thenCorrect() {
String s = "Welcome to Baeldung";
String[] expected1 = new String[] { "Welcome", "to", "Baeldung" };
String[] expected2 = new String[] { "Welcome", "to Baeldung" };
assertArrayEquals(expected1, s.split(" "));
assertArrayEquals(expected2, s.split(" ", 2));
}
异常
-
PatternSyntaxException
- 无效分隔符。
@Test(expected = PatternSyntaxException.class)
public void whenPassInvalidParameterToSplit_thenPatternSyntaxExceptionThrown() {
String s = "Welcome*to Baeldung";
String[] result = s.split("*");
}