数字字母组成的ID或Code,自增方法
在项目实践中,某表的ID是由8为数字或字母的字符串组成,调用接口时请求方只需要传入其他参数,ID由系统自动生成。
public class CalculateUtil {
/**
* 数字和字母组成的ID自动累加方法
* ASCII码:[48-57]-[97-122]-[65-90]
* 字符: [0-9]-[a-z]-[A-Z]
*/
public static String idAutoIncrease62(String tranCode) {
if (StringUtils.isBlank(tranCode)) {
return null;
}
char[] array = tranCode.toCharArray();
for (int point = tranCode.length() - 1; point >= 0; point--) {
int nextIndex = getNextIndex(tranCode.charAt(point));
array[point] = (char) nextIndex;
if (nextIndex == 48) {
continue;
}
return Arrays.toString(array);
}
return null;
}
private static int getNextIndex(char point) {
int index = point;
switch (index) {
case 57:
/**9->a*/
return 97;
case 122:
/**z->A*/
return 65;
case 90:
/**Z->0*/
return 48;
default:
/**累加一*/
return ++index;
}
}
public static void main(String[] args) {
String str = "0000";
String str3 = "0009";
String str4 = "000z";
String str2 = "0ZZZ";
String str6 = "ZZZ";
System.out.println(idAutoIncrease62(str));
System.out.println(idAutoIncrease62(str3));
System.out.println(idAutoIncrease62(str4));
System.out.println(idAutoIncrease62(str2));
System.out.println(idAutoIncrease62(str6));
}
}