前两篇博文简单分享了一下数字工具类,现在说说字符串工具类。相信大家都自己封装过或者用过guava封装的Strings,但是有没有可以智能截取,比如说“截取整数第二个到倒数第二个”的字符串。你是否还需要自己写str.substring
相信大家都自己封装过或者用过guava封装的Strings,但是有没有可以智能截取,比如说“截取整数第二个到倒数第二个”的字符串。你是否还需要自己写str.substring(1,str.length()-2)。如果是的话,请继续往下看吧。暂时还未见过可以反向截取字符串的。一般都是substring(str, start, end)或者substring(str, len);而这里的参数都必须是正数,否则就会报错。所以为了改善这些方法,我简单封装了一下substring这个方法,提供了4种最常用的方法:
具体代码如下:
public static String subStrStart(String str, int end){ return subStr(str, 0, end); } public static String subStrEnd(String str, int start){ return subStr(str, str.length()-start, str.length()); } public static String subStr(String str, int length) throws RuntimeException{ if(str==null){ throw new NullPointerException("字符串为null"); } int len = str.length(); if(len<Math.abs(length)){ throw new StringIndexOutOfBoundsException("最大长度为"+len+",索引超出范围为:"+(len-Math.abs(length))); } if(length>=0){ return subStr(str, 0,length); }else{ return subStr(str, len-Math.abs(length), len); } } public static String subStr(String str, int start, int end) throws RuntimeException{ if(str==null){ throw new NullPointerException(""); } int len = str.length(); int s = 0;//记录起始索引 int e = 0;//记录结尾索引 if(len<Math.abs(start)){ throw new StringIndexOutOfBoundsException("最大长度为"+len+",索引超出范围为:"+(len-Math.abs(start))); }else if(start<0){ s = len - Math.abs(start); }else if(start<0){ s=0; }else{//>=0 s = start; } if(len<Math.abs(end)){ throw new StringIndexOutOfBoundsException("最大长度为"+len+",索引超出范围为:"+(len-Math.abs(end))); }else if (end <0){ e = len - Math.abs(end); }else if (end==0){ e = len; }else{//>=0 e = end; } if(e<s){ throw new StringIndexOutOfBoundsException("截至索引小于起始索引:"+(e-s)); } return str.substring(s, e); }
--结束END--
本文标题: Java常用字符串工具类 字符串智能截取(3)
本文链接: https://www.lsjlt.com/news/226411.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0