Java字符串易错方法总结

Java字符串易错方法总结

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

1306719-20180821142138010-4186569.png

  • limit为0时,数组的个人为全部分割的总个数;limit为1时,数组个数为1个;limit为2时,数组的个数为2个。
  • Example
import org.junit.Test;

public class SplitExample {
    @Test
    public void test1() {
        String s1 = "welcome to split world";
        System.out.println("returning words:");
        for (String w : s1.split("\\s", 0)) {
            System.out.println(w);
        }
        System.out.println(s1.split("\\s", 0).length);
        System.out.println("returning words:");
        for (String w : s1.split("\\s", 1)) {
            System.out.println(w);
        }
        System.out.println(s1.split("\\s", 1).length);
        System.out.println("returning words:");
        for (String w : s1.split("\\s", 2)) {
            System.out.println(w);
        }
        System.out.println(s1.split("\\s", 2).length);
        System.out.println("---------------------------------");
    }

    @Test
    public void test2() {
        String str = "Javatpointtt";
        System.out.println("Returning words:");
        String[] arr = str.split("t", 0);
        for (String w : arr) {
            System.out.println(w);
        }
        System.out.println("Split array length: " + arr.length);
    }
}
  • Result
    Java字符串易错方法总结_第1张图片

转载于:https://www.cnblogs.com/hglibin/p/9511081.html

你可能感兴趣的:(Java字符串易错方法总结)