java使字符串的數字加一


/**

* 字符串+1方法,該方法將其結尾的整數+1,適用於任何以整數結尾的字符串,不限格式,不限分隔符。
* @author zxcvbnmzb
* @param testStr 要+1的字符串
* @return +1后的字符串
* @exception NumberFormatException
*/
public  static  String addOne(String testStr){
     String[] strs = testStr.split( "[^0-9]" ); //根據不是數字的字符拆分字符串
     String numStr = strs[strs.length- 1 ]; //取出最后一組數字
     if (numStr !=  null  && numStr.length()> 0 ){ //如果最后一組沒有數字(也就是不以數字結尾),拋NumberFormatException異常
         int  n = numStr.length(); //取出字符串的長度
         int  num = Integer.parseInt(numStr)+ 1 ; //將該數字加一
         String added = String.valueOf(num);
         n = Math.min(n, added.length());
         //拼接字符串
         return  testStr.subSequence( 0 , testStr.length()-n)+added;
     } else {
         throw  new  NumberFormatException();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM