1

String我需要按升序对以下数组进行排序。

String str[] = {"ASE", "LSM", "BSE", "LKCSE", "DFM"};

怎么做?我需要帮助。

4

3 回答 3

5

此答案基于SignareHeartBeat的建议。浏览此链接了解详情。另外这个链接,使用 java.util.Array 排序可能会有所帮助。

// Initialization of String array 
String strs[] = {"One", "Two", "Threee", "Four", "Five", "Six", "Seven"};

// implementation of Comparator
Comparator strComparator = new Comparator() {
    public int compare(Object o1, Object o2) {
        return o1.toString().compareTo(o2.toString());
    }
};

// Sort
Arrays.sort(strs, strComparator);
于 2012-05-29T17:45:19.167 回答
0

Here is my solution:-

String str[]={"ASE","LSM","BSE","LKCSE","DFM"};

for(int j = 0; j < str.length; j++){
               for(int i = j + 1; i < str.length; i++) {
                   if(str[i].compareTo(str[j]) < 0) {
                       String t = str[j];
                       str[j] = str[i];
                       str[i] = t;
                   }
               }

    }
于 2012-05-30T09:32:22.367 回答
0

尝试这个 -

import java.util.*;
import java.io.*;

public class TestSort1 {

String [] words = { "Réal", "Real", "Raoul", "Rico" };

 public static void main(String args[]) throws Exception {
    try {
  Writer w = getWriter();
  w.write("Before :\n");

  for (String s : words) {
    w.write(s + " ");
  }

  java.util.Arrays.sort(words);

  w.write("\nAfter :\n");
  for (String s : words) {
    w.write(s + " ");
  }
  w.flush();
  w.close();
}
catch(Exception e){
  e.printStackTrace();
}

 }

// useful to output accentued characters to the console
  public static Writer getWriter() throws UnsupportedEncodingException {
    if (System.console() == null) {
      Writer w =
        new BufferedWriter
         (new OutputStreamWriter(System.out, "Cp850"));
      return w;
    }
    else {
      return System.console().writer();
    }
  }
}
于 2012-05-29T12:32:52.580 回答