欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java split用法详解及实例代码

程序员文章站 2024-03-13 14:42:21
public string[] split(string regex) 默认limit为0 public string[] split(string regex, int...

public string[] split(string regex) 默认limit为0

public string[] split(string regex, int limit)

当limit>0时,则应用n-1次

public static void main(string[] args) {
    string s = "boo:and:foo";
    string[] str = s.split(":",2);
    system.out.print(str[0] + "," + str[1]);
 }

结果:

boo,and:foo

当limit<0时,则应用无限次

public static void main(string[] args) {
    string s = "boo:and:foo";
    string[] str = s.split(":",-2);
    for(int i = 0 ; i < str.length ; i++){
      system.out.print(str[i] + " ");
    }
 }

结果:

boo and foo

当limit=0时,应用无限次并省略末尾的空字符串

public static void main(string[] args) {
    string s = "boo:and:foo";
    string[] str = s.split("o",-2);
    for(int i = 0 ; i < str.length ; i++){
      if( i < str.length - 1)
      system.out.print("(" + str[i] + "),");
      else
      system.out.print("(" + str[i] + ")");
    }
 }

结果:

(b),(),(:and:f),(),()

public static void main(string[] args) {
    string s = "boo:and:foo";
    string[] str = s.split("o",0);
    for(int i = 0 ; i < str.length ; i++){
      if( i < str.length - 1)
      system.out.print("(" + str[i] + "),");
      else
      system.out.print("(" + str[i] + ")");
    }
 }

结果:

(b),(),(:and:f)

以上就是对java split 的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!