排序字符串的自定义排序的数组 [英] Sorting an array of String with custom ordering

查看:179
本文介绍了排序字符串的自定义排序的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组:

 的String []海峡= {AB,雾,狗,汽车,床};
 Arrays.sort(STR);
 的System.out.println(Arrays.toString(STR));

如果我用 Arrays.sort ,输出是:

  [AB,床,汽车,狗,雾]

但我需要实现以下顺序:

FCBWHJLOAQUXMPVINTKGZERDYS

我想我需要实施比较并重写比较方法:

  Arrays.sort(STR,新的比较<串GT;(){        @覆盖
        公众诠释比较(字符串O1,O2的字符串){
            // TODO自动生成方法存根
            返回0;
        }
    });

我应该如何去解决呢?


解决方案

 最后弦乐ORDER =FCBWHJLOAQUXMPVINTKGZERDYS;Arrays.sort(STR,新的比较<串GT;(){    @覆盖
    公众诠释比较(字符串O1,O2的字符串){
       返回ORDER.indexOf(01) - ORDER.indexOf(02);
    }
});

您还可以添加:

  o1.toUpperCase()

如果您的阵列情况下,敏感的。


显然,OP需要比较不仅字母,但字母串,所以这是一个比较复杂:

 公众诠释比较(字符串O1,O2的字符串){
       INT POS1 = 0;
       INT POS2 = 0;
       对(INT I = 0; I&下; Math.min(o1.length(),o2.length())及&放大器; POS1 == POS2;我++){
          POS1 = ORDER.indexOf(o1.charAt(I));
          POS2 = ORDER.indexOf(o2.charAt(I));
       }       如果(POS1 == POS2&放大器;&放大器;!o1.length()= o2.length()){
           返回o1.length() - o2.length();
       }       返回POS1 - POS2;
    }

I have a String array:

 String[] str = {"ab" , "fog", "dog", "car", "bed"};
 Arrays.sort(str);
 System.out.println(Arrays.toString(str));

If I use Arrays.sort, the output is:

 [ab, bed, car, dog, fog]

But I need to implement the following ordering:

FCBWHJLOAQUXMPVINTKGZERDYS

I think I need to implement Comparator and override compare method:

 Arrays.sort(str, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            // TODO Auto-generated method stub
            return 0;
        }
    });

How should I go about solving this?

解决方案

final String ORDER= "FCBWHJLOAQUXMPVINTKGZERDYS";

Arrays.sort(str, new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {
       return ORDER.indexOf(o1) -  ORDER.indexOf(o2) ;
    }
});

You can also add:

o1.toUpperCase()

If your array is case in-sensitive.


Apparently the OP wants to compare not only letters but strings of letters, so it's a bit more complicated:

    public int compare(String o1, String o2) {
       int pos1 = 0;
       int pos2 = 0;
       for (int i = 0; i < Math.min(o1.length(), o2.length()) && pos1 == pos2; i++) {
          pos1 = ORDER.indexOf(o1.charAt(i));
          pos2 = ORDER.indexOf(o2.charAt(i));
       }

       if (pos1 == pos2 && o1.length() != o2.length()) {
           return o1.length() - o2.length();
       }

       return pos1  - pos2  ;
    }

这篇关于排序字符串的自定义排序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆