Sort on a string that may contain a number

前端 未结 23 2322
走了就别回头了
走了就别回头了 2020-11-22 02:59

I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the strin

23条回答
  •  日久生厌
    2020-11-22 03:30

    interesting problem, and here my proposed solution:

    import java.util.Collections;
    import java.util.Vector;
    
    public class CompareToken implements Comparable
    {
        int valN;
        String valS;
        String repr;
    
        public String toString() {
        return repr;
        }
    
        public CompareToken(String s) {
        int l = 0;
        char data[] = new char[s.length()];
        repr = s;
        valN = 0;
        for (char c : s.toCharArray()) {
            if(Character.isDigit(c))
            valN = valN * 10 + (c - '0');
            else
            data[l++] = c;
        }
    
        valS = new String(data, 0, l);
        }
    
        public int compareTo(CompareToken b) {
        int r = valS.compareTo(b.valS);
        if (r != 0)
            return r;
    
        return valN - b.valN;
        }
    
    
        public static void main(String [] args) {
        String [] strings = {
            "aaa",
            "bbb3ccc",
            "bbb12ccc",
            "ccc 11",
            "ffffd",
            "eee3ffffdjpeg2000eee",
            "eee12ffffdjpeg2000eee"
        };
    
        Vector data = new Vector();
        for(String s : strings)
            data.add(new CompareToken(s));
        Collections.shuffle(data);
    
        Collections.sort(data);
        for (CompareToken c : data)
            System.out.println ("" + c);
        }
    
    }
    

提交回复
热议问题