关于java中split的使用

    之前在http://shukuiyan.iteye.com/blog/507915文中已经叙述过这个问题,但是最近一次笔试中居然有碰到了这个知识点,而且还做错了,囧!学艺不精啊。题目大概是这样的:

String s2="this is a test";
String sarray[]=s2.split("/s");
System.out.println("sarray.length="+sarray.length);

这个输出是什么还是编译出错?我想那个split方法中的参数要是"s"的话,输出一定是4了,就是将原来字符串分成了数组{"thi","i","a te","t"},但是原题split方法中的参数要是"/s",那么这个参数到底是嘛意思呢,实验后输出结果居然是1。

原因还得深究啊。

 

    java.lang.string.split,即split 方法,它实现的功能是将一个字符串分割为子字符串,然后将结果作为字符串数组返回。 格式为:

                 stringObj.split([separator,[limit]])
其中stringObj是必选项,表示要被分解的 String 对象或文字。该对象不会被 split 方法修改。 separator 为可选项,表示字符串或正则表达式对象,它标识了分隔字符串时使用的是一个还是多个字符。如果忽略该选项,返回包含整个字符串的单一元素数组。 limit 为可选项,该值用来限制返回数组中的元素个数。 值得注意的是: split 方法的结果是一个字符串数组,在 stingObj 中每个出现 separator 的位置都要进行分解,separator 不作为任何数组元素的部分返回。

一个例子

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);
}

这样输出结果为

this
is
a
about
split
test

另一个:

this

is
a
about
split

test

另外一个例子

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);
}
这个输出为空,为什么呢?

因为 public string[] split(string regex) 这里的参数的名称是regex ,也就是 regular expression (正则表达式)。这个参数并不是一个简单的分割用的字符,而是一个正则表达式,以下是split 方法的实现代码:
   public string[] split(string regex, int limit) {
        return pattern.compile(regex).split(this, limit);
   }

split 的实现直接调用的 matcher 类的 split 的方法。我们知道,“ . ”在正则表达式中有特殊的含义,因此我们使用的时候必须进行转义。 只要将

String iparray[]=ipstring.split(".");

 

改为

String iparray[]=ipstring.split("\\.");


就可以了。

那么这里在列上一些转义字符

 \\ 反斜杠
\t
间隔 ('\u0009')
\n
换行 ('\u000A')
\r
回车 ('\u000D')
\d
数字 等价于 [0-9]
\D
非数字 等价于 [^0-9]
\s
空白符号 [\t\n\x0B\f\r]
\S
非空白符号 [^

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值