需求分析
1骡尽、防止重名肝箱,把字符串末尾添加數(shù)字
2印机、末尾沒有數(shù)字的,自動添加數(shù)字瓶殃,數(shù)字從2開始
舉例
例如:
abc =》 abc2
你好1 =》你好2
實(shí)現(xiàn)
/**
* 獲取字符串最后的一組數(shù)字,返回最后數(shù)字+1字符串
* @param str
* @return
*/
public static String toStringLastNumAddOne(String str) {
StringBuilder sb = new StringBuilder(str + "0");
// 默認(rèn)添加一個0 分割數(shù)組
String[] str2 = sb.toString().split("[^0-9]");
// 取出最后一組的數(shù)字
StringBuilder lastStr = new StringBuilder(str2[str2.length - 1]);
// 刪除字符串
sb.delete(sb.length() - lastStr.length(), sb.length());
// 判定如果最后一組數(shù)字的長度等于1副签,說明是原字符串末尾就沒有數(shù)字遥椿,則拼接默認(rèn)數(shù)字2
return sb.append(lastStr.length() == 1 ? "2" :
Integer.parseInt(lastStr.deleteCharAt(lastStr.length() - 1).toString())+ 1)
.toString();
}