Home >Java >javaTutorial >Detailed explanation of java split usage and example code

Detailed explanation of java split usage and example code

高洛峰
高洛峰Original
2017-01-18 15:43:391651browse

public String[] split(String regex) The default limit is 0

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

When limit>0, n- is applied 1 time

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

Result:

boo,and:foo

When limit<0, apply unlimited times

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] + " ");
    }
 }

Result:

boo and foo

When limit=0, apply infinite times and omit the empty string at the end

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] + ")");
    }
 }

Result:

(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] + ")");
    }
 }

Result:

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

The above is the collection of information on Java split. We will continue to add relevant information in the future. Thank you for your support of this site!

For more detailed explanations of java split usage and sample code related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn