java 字符串按ascii排序 string str="action[0],action[1],action[8],action[11]",TreeMap实现

91 阅读1分钟

public static void main(String[] args) {
String str = "action[0],action[1],action[2],action[3],action[4],action[5],action[6],action[7],action[10],action[11],action[12]";

// 分割字符串并提取action及其索引
String[] parts = str.split(",");
TreeMap<String, Integer> sortedActions = new TreeMap<>();

for (String part : parts) {
// 提取action和索引
String actionWithIndex = part.trim();
int openBracketIndex = actionWithIndex.indexOf("[");
String actionName = actionWithIndex.substring(0, openBracketIndex);
String indexStr = actionWithIndex.substring(openBracketIndex + 1, actionWithIndex.length() - 1);
int index = Integer.parseInt(indexStr);

// 将action名称与索引作为键值对放入TreeMap中
sortedActions.put(actionName + "[" + index + "]", index);
}

// 打印排序后的结果
for (Map.Entry<String, Integer> entry : sortedActions.entrySet()) {
System.out.println(entry.getKey());
}
}