Java Pattern split(CharSequence,int)方法及示例

来源:这里教程网 时间:2026-02-17 21:05:12 作者:

Java Pattern split(CharSequence,int)方法及示例

Pattern 类的 split(CharSequence,int) 方法用于将作为参数传递给方法的给定字符序列分割成与此模式匹配的字符串。数组中的子串是按照它们在输入中出现的顺序排列的。如果这个模式不匹配输入的任何子序列,那么返回的数组只有一个元素,即字符串形式的输入序列。以int形式传递的limit参数有助于计算模式的应用次数,并影响到结果数组的长度。如果极限值n大于0,那么该模式最多应用n-1次。如果n为非正数或零,那么该模式将被尽可能多地应用。

语法

public String[] split?(CharSequence input, int limit)

参数: 该方法接受两个参数,一个是代表要分割的字符序列的输入,另一个是代表描述中提到的结果阈值的限制。

返回值: 该方法返回通过分割该模式周围的输入数据计算出来的字符串数组。

以下程序说明了 split(CharSequence, int) 方法。

程序1 :

// Java program to demonstrate// Pattern.split(CharSequence) method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {        // create a REGEX String        String REGEX = "geeks";          // create the string        // in which you want to search        String actualString            = "Welcome to geeks for geeks";          // create a Pattern using REGEX        Pattern pattern = Pattern.compile(REGEX);          // create limit to 2        // so it can applied at most limit - 1 time        int limit = 2;          // split the text        String[] array            = pattern.split(actualString, limit);          // print array        for (int i = 0; i < array.length; i++) {            System.out.println("array[" + i                               + "]=" + array[i]);        }    }}

输出:

array[0]=Welcome to array[1]= for geeks

程序2

// Java program to demonstrate// Pattern.split(CharSequence) method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {        // create a REGEX String        String REGEX = "ee";          // create the string        // in which you want to search        String actualString            = "aaeebbeecceeddee";          // create a Pattern using REGEX        Pattern pattern = Pattern.compile(REGEX);          // create limit to 2        // so it can applied at most limit - 1 time        int limit = 0;          // split the text        String[] array            = pattern.split(actualString, limit);          // print array        for (int i = 0; i < array.length; i++) {            System.out.println("array[" + i                               + "]=" + array[i]);        }    }}

输出:

array[0]=aaarray[1]=bbarray[2]=ccarray[3]=dd

**参考资料: ** https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#split(java.lang.CharSequence, int)

相关推荐