String类的分割方法split

测试用例:
import java.util.Arrays;

public class Demo02 {
    public static void main(String[] args) {
//字符串变量a
        String a="Solutions to selected exercises can be found in the electronic document.The Thinking in Java Annotated Solution Guide,available for small fee from Bruceeckel.";
//通过split进行分割,将字符串分割存储到数组b中
        String [] b=a.split(" |,|\\.");
//将数组遍历
        System.out.println(Arrays.toString(b));
    }
}

运行结果:

[Solutions, to, selected, exercises, can, be, found, in, the, electronic, document, The, Thinking, in, Java, Annotated, Solution, Guide, available, for, small, fee, from, Bruceeckel]

*值得注意的是字符串变量中含有 ’空格 ‘   ‘ ,’ 以及 ‘.’ , 所以我们在split的参数中需要传递三个符号,当我们对字符串进行分割时需要对多个符号进行分割,我们需要使用 | 。

最后最重要的一点是对于某些符号如 '.'  '|'  '*'  等符号如果要是这些符号作为分隔符则需要前面加\\来加以转义如案例 electronic document.The 中的 ’.‘


版权声明:本文为weixin_59443832原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。