Java字符串split()方法
split()
方法会在指定的正则表达式处分割字符串,并返回一个子字符串数组。
示例
class Main {
public static void main(String[] args) {
String text = "Java is a fun programming language";
// 从空格处分割字符串
String[] result = text.split(" ");
System.out.print("result = ");
for (String str : result) {
System.out.print(str + ", ");
}
}
}
// 输出: result = Java, is, a, fun, programming, language,
String split() 的语法
字符串 split()
方法的语法是:
string.split(String regex, int limit)
这里,string
是 String
类的一个对象 。
split() 参数
字符串 split()
方法可以接受两个参数:
- regex - 字符串会在此正则表达式处分割(可以是字符串)
- limit (可选)- 控制结果子字符串的数量
如果没有传递 limit
参数,split()
会返回所有可能的子字符串。
split() 的返回值
- 返回一个子字符串数组
注意: 如果传递给 split()
的正则表达式无效,split()
方法会抛出 PatternSyntaxExpression
异常。
示例 1:没有 limit 参数的 split()
// 导入 Arrays 以将数组转换为字符串
// 用于打印数组
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String vowels = "a::b::c::d:e";
// 在 "::" 处分割字符串
// 将结果存储在字符串数组中
String[] result = vowels.split("::");
// 将数组转换为字符串并打印
System.out.println("result = " + Arrays.toString(result));
}
}
输出
result = [a, b, c, d:e]
这里,我们在 ::
处分割字符串。由于没有传递 limit
参数,返回的数组包含了所有子字符串。
带有 limit 参数的 split()- 如果 limit
参数为 0 或负数,split()
会返回包含所有子字符串的数组。
- 如果
limit
参数为正数(比如说n
),split()
会返回最多n
个子字符串。
示例 2:带有 limit 参数的 split()
// 导入 Arrays 以将数组转换为字符串
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String vowels = "a:bc:de:fg:h";
// 在 ":" 处分割数组
// limit 为 -2;数组包含所有子字符串
String[] result = vowels.split(":", -2);
System.out.println("limit 为 -2 时的结果 = " + Arrays.toString(result));
// limit 为 0;数组包含所有子字符串
result = vowels.split(":", 0);
System.out.println("limit 为 0 时的结果 = " + Arrays.toString(result));
// limit 为 2;数组最多包含 2 个子字符串
result = vowels.split(":", 2);
System.out.println("limit 为 2 时的结果 = " + Arrays.toString(result));
// limit 为 4;数组最多包含 4 个子字符串
result = vowels.split(":", 4);
System.out.println("limit 为 4 时的结果 = " + Arrays.toString(result));
// limit 为 10;数组最多包含 10 个子字符串
result = vowels.split(":", 10);
System.out.println("limit 为 10 时的结果 = " + Arrays.toString(result));
}
}
输出
limit 为 -2 时的结果 = [a, bc, de, fg, h]
limit 为 0 时的结果 = [a, bc, de, fg, h]
limit 为 2 时的结果 = [a, bc:de:fg:h]
limit 为 4 时的结果 = [a, bc, de, fg:h]
limit 为 10 时的结果 = [a, bc, de, fg, h]
注意: split() 方法将正则表达式作为第一个参数。如果你需要使用特殊字符,例如:\
、|
、^
、*
、+
等,你需要转义这些字符。例如,我们需要使用 \\+
来在 +
处分割。
示例 3:在 + 字符处使用 split()
// 导入 Arrays 以将数组转换为字符串
// 用于打印数组
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String vowels = "a+e+f";
// 在 "+" 处分割字符串
String[] result = vowels.split("\\+");
// 将数组转换为字符串并打印
System.out.println("result = " + Arrays.toString(result));
}
}
输出
result = [a, e, f]
这里,为了在 +
处分割字符串,我们使用了 \\+
。这是因为 +
是一个特殊字符(在正则表达式中有特殊含义)。