java.lang.string.split,即split 方法,它实现的功能是将一个字符串分割为子字符串,然后将结果作为字符串数组返回。 格式为:
stringObj.split([separator,[limit]])
stringObj 为被分割的字符串,split操作不会改变他的值。
separator 表示字符串或正则表达式对象,它标识了分隔字符串时使用的是一个还是多个字符。
limit 为可选项,该值用来限制返回数组中的元素个数。
一个例子
- String srcstring="this is a about split test";
- String stringarray[]=srcstring.split(" ");
- 在每个空格字符处进行分解
- for(String stemp:stringarray){
- System.out.println(stemp);
- }
- String srcstring1=" this is a about split test";//有n个空格的话,分成的数组长度为n+1
- //如果字符串中有多个空格时,则两个空格间认为是没有字符,结果字符串数组中该位置为空。
- String stringarray1[]=srcstring1.split(" ");
- for(String stemp:stringarray1){
- System.out.println(stemp);
- }
这样输出结果为
另外一个例子
- String srcstring="this is a about split test";
- String stringarray[]=srcstring.split(" ",2);
- 在每个空格字符处进行分解
- for(String stemp:stringarray){
- System.out.println(stemp);
- }
- 输出结果为
- this
- is a about split test
如果分割符包含正则表达是,则需要用反斜杠来转义 \\
看看下面这个
- String ipstring="59.64.159.224";
- String iparray[]=ipstring.split(".");
- for(String stemp:iparray){
- System.out.println(stemp);
- }
- 这个输出为空,为什么呢?
改为