使用可比较或比较器接口使用String s1的顺序对String s2进行排序

时间:2013-03-25 14:51:04

标签: java string comparator comparable

我有两个字符串s1和s2,我想根据s1中字母的出现顺序对s2进行排序,如果在s2中留下其他字母,则按字母顺序对它们进行排序。

假设我有以下内容;

String s1 =“war”;

String s2 =“它真是一个程序员”;

输出:waaarrrIbeeeeggimmmnoopsst。

我已经写了一个代码来做到这一点虽然buut我想知道它是否可能使用比较器/类似的接口来解决它。

下面列出的是我的代码段。

public class Sort {

    private static String a = "war";
    private static String b = "Its awesome being a programmer";
    static List<Character> list = new ArrayList<>();

    static public void main(String[] args) {
        Character s;
        Character x;

        System.out.println("String to be sorted: '" + b + "'");
        System.out.println("Key for sort: '" + a + "'");

        /* 
         * put all the string in a list 
         */
        for (int i = 0; i < b.length(); i++) {
            s = b.charAt(i);
            if (s != ' ') {
                list.add(s);
            }
        }
        /* 
         * compare individual chac in key with individaul char in string to sort 
         */
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < a.length(); j++) {
            x = a.charAt(j);
            for (int k = 0; k < b.length(); k++) {
                s = b.charAt(k);
                if (x == s) {
                    sb.append(s);
                    list.remove(x);
                }
            }
        }

        /* 
         * check if list is empty if not, sort and append the rest to the stringbuilder 
         */
        if (!list.isEmpty()) {
            Collections.sort(list);
            for (char c : list) {
                sb.append(c);
            }
        }
        System.out.println("Sorted version of string: '" + sb.toString() + "'");
    }
}

3 个答案:

答案 0 :(得分:2)

private static String a = "war";
private static String b = "Its awesome being a programmer".replace(" ","");
private static String answer = "waaarrrIbeeeeggimmmnoopsst";

public static void main(String[] args) {
    List<String> characters = new ArrayList<String>(b.length());
    for (int i=0;i<b.length();i++){
        characters.add(String.valueOf(b.charAt(i)));
    }
    Collections.sort(characters,new CompareIt(a));
    String sortedString = listToString(characters);
    System.out.println(sortedString);
    System.out.println(answer);
    System.out.println(answer.equals(sortedString));
}
private static String listToString(List<String> listOfStrings){
    StringBuilder builder = new StringBuilder();
    for (String str : listOfStrings){
        builder.append(str);
    }
    return builder.toString();
}
private static class CompareIt implements Comparator<String>{

    private final String source;

    public CompareIt(String source) {
        super();
        this.source = source;
    }

    public int compare(String o1, String o2) {
        int i1 = source.indexOf(o1);
        int i2 = source.indexOf(o2);
        if (i1==-1 && i2!=-1){
            return 1;
        } else if (i1!=-1 && i2==-1){
            return -1;
        } else if (i1!=-1 && i2!=-1){
            return i1 > i2 ? 1:-1;
        } else {
            return o1.compareTo(o2);
        }
    }

}

这似乎有效。 编辑:要包含sysout,结果与提供的预期答案匹配。 EDIT2:Typo与我的最终索引比较? 1:0而不是1:-1。

答案 1 :(得分:1)

public static void main(String[] args) {
    String s1 = "war";
    String s2 = "Its awesome being a programmer";
    String result = "";
    for (int i = 0; i < s1.length(); i++) {
        int len = s2.length()
                - s2.replace(String.valueOf(s1.charAt(i)), "").length();
        s2 = s2.replace(String.valueOf(s1.charAt(i)), "").replace(" ", "");
        for (int j = 0; j < len; j++)
            result = result + String.valueOf(s1.charAt(i));
    }
    char[] remaining = s2.toCharArray();
    Arrays.sort(remaining);
    for (Character c : remaining)
        result = result + String.valueOf(c);

    System.out.println(result);
}

试试这个:我试过没有使用任何界面。

输出:

waaarrrIbeeeeggimmmnoopsst

答案 2 :(得分:1)

public static Comparator<Character> compareOn(final String key) {
    return new Comparator<Character>() {
        public int compare(Character c1, Character c2) {
            final int indexInKey1 = key.indexOf(c1);
            final int indexInKey2 = key.indexOf(c2);
            final int result;
            if (indexInKey1 == -1 && indexInKey2 == -1) {
                result = c1.compareTo(c2); //fall back to natural ordering
            } else {
                if (indexInKey1 == -1) {
                    result = 1;
                } else if (indexInKey2 == -1) {
                    result = -1;
                } else {
                    result = indexInKey1 - indexInKey2;
                }
            }
            return result;
        }
    };
}

public static void main(String[] args) {
    final String a = "war";
    final String b = "Its awesome being a programmer";
    final List<Character> chars = new ArrayList<Character>();
    for (char c: b.toCharArray()) {
        if (c != ' ') {
          chars.add(c);
        }
    }
    Collections.sort(chars, compareOn(a));
    System.out.println(chars);
}