Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 按字典顺序和数字顺序对字符串数组排序(因为字符串包含数字)_Java_String - Fatal编程技术网

Java 按字典顺序和数字顺序对字符串数组排序(因为字符串包含数字)

Java 按字典顺序和数字顺序对字符串数组排序(因为字符串包含数字),java,string,Java,String,我有一个包含数字的字符串。我想对它进行排序,就像输出应该按字典顺序排序,然后根据最后的数字排序一样。我已经在下面的方式做了这一点的复杂性是非常大的。有没有其他方法来分类? 不想使用数组。直接排序 预期输出-[blue1、blue3、red3、red6] public class SortStrings { public static void main(String[] args) { String a[] = { "blue3", "red6", "red3","blue1" }

我有一个包含数字的字符串。我想对它进行排序,就像输出应该按字典顺序排序,然后根据最后的数字排序一样。我已经在下面的方式做了这一点的复杂性是非常大的。有没有其他方法来分类? 不想使用数组。直接排序

预期输出-[blue1、blue3、red3、red6]

 public class SortStrings {

public static void main(String[] args) {

    String a[] = { "blue3", "red6", "red3","blue1" };
    String tmp;
    for (int i = 0; i < a.length; i++) {
        for (int j = i; j < a.length - i-1; j++) {
            if (a[j].compareTo(a[j + 1]) > 0) {
                tmp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = tmp;
            }
        }
    }
    List<String> strings = Arrays.asList(a);
      Collections.sort(strings, new Comparator<String>() {
            public int compare(String o1, String o2) {
                return extractInt(o1) - extractInt(o2);
            }

            int extractInt(String s) {
                String num = s.replaceAll("\\D", "");
                // return 0 if no digits found
                return num.isEmpty() ? 0 : Integer.parseInt(num);
            }
        });
    System.out.println(Arrays.toString(a));
}
公共类排序字符串{
公共静态void main(字符串[]args){
字符串a[]={“blue3”、“red6”、“red3”、“blue1”};
串tmp;
for(int i=0;i0){
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
}
}
List strings=Arrays.asList(a);
Collections.sort(字符串、新比较器(){
公共整数比较(字符串o1、字符串o2){
返回extractInt(o1)-extractInt(o2);
}
int extractInt(字符串s){
字符串num=s.replaceAll(“\\D”和“);
//如果找不到数字,则返回0
返回num.isEmpty()?0:Integer.parseInt(num);
}
});
System.out.println(Arrays.toString(a));
}

}

什么是“词典和数字”呢?您希望从示例数据中看到什么结果?嗨@KevinAnderson-我已经更新了我的问题,我希望现在问题更清楚。谢谢你指出。如果数据是,比如说,{red25,blue3,red6,blue19}:那应该排序为{blue3,blue19,red6,red25},而不是{blue19,blue3,red25,red6}吗?你首先要按字典顺序对整个列表进行排序,然后,您将按照末尾的数字对整个列表进行排序-因此将删除第一次排序的结果!我想你想要的是一个比较器,它首先通过前导的非数字进行比较,然后只有当它与末尾的数字相等时才进行比较。如果你在列表中添加“blue201”会怎么样?它会在哪里结束?