java split

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

                 stringObj.split([separator,[limit]]) 

stringObj 为被分割的字符串,split操作不会改变他的值。

separator 表示字符串或正则表达式对象,它标识了分隔字符串时使用的是一个还是多个字符。

limit 为可选项,该值用来限制返回数组中的元素个数。

一个例子

Java代码   收藏代码
  1. String srcstring="this is a about split test";  
  2. String stringarray[]=srcstring.split(" ");  
  3.  在每个空格字符处进行分解  
  4. for(String stemp:stringarray){  
  5.     System.out.println(stemp);  
  6. }  
  7. String srcstring1=" this  is a about split  test";//有n个空格的话,分成的数组长度为n+1  
  8. //如果字符串中有多个空格时,则两个空格间认为是没有字符,结果字符串数组中该位置为空。  
  9. String stringarray1[]=srcstring1.split(" ");  
  10. for(String stemp:stringarray1){  
  11.     System.out.println(stemp);  
  12. }  

这样输出结果为

Java代码   收藏代码
  1. this  
  2. is  
  3. a  
  4. about  
  5. split  
  6. test  
  7.   
  8. 另一个:  
  9.   
  10. this  
  11.   
  12. is  
  13. a  
  14. about  
  15. split  
  16.   
  17. test  

另外一个例子

Java代码   收藏代码
  1. String srcstring="this is a about split test";  
  2. String stringarray[]=srcstring.split(" ",2);  
  3.  在每个空格字符处进行分解  
  4. for(String stemp:stringarray){  
  5.        System.out.println(stemp);  
  6. }  
  7. 输出结果为  
  8. this  
  9. is a about split test  

 

如果分割符包含正则表达是,则需要用反斜杠来转义 \\

看看下面这个

Java代码   收藏代码
  1. String ipstring="59.64.159.224";  
  2. String iparray[]=ipstring.split(".");  
  3. for(String stemp:iparray){  
  4.     System.out.println(stemp);  
  5. }  
  6. 这个输出为空,为什么呢?  

Java代码   收藏代码
  1. String iparray[]=ipstring.split(".");  

 

改为

Java代码   收藏代码
  1. String iparray[]=ipstring.split("\\.");  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值