我已經寫了一個java程序在java中按字母順序排序字符串。問題是,當它排序,將其視爲字符具有串羅馬數字,並相應地進行排序在java中自定義字符串排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class SampleCustomSortApp
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
ArrayList<String> titles =new ArrayList();
titles.add("java");
titles.add("J-IV");
titles.add("A-V");
titles.add("J-V");
titles.add("J-IX");
titles.add("J-XX");
titles.add("J-X");
titles.add("J-I");
titles.add("J-II");
titles.add("datawarehouse");
titles.add("oracledba");
System.out.println("Before Sorting Elements Are :"+titles+"\n");
Collections.sort(titles, new MyCustomCompator());
System.out.println("After Sorting Elements Are :"+titles);
}
}
class MyCustomCompator implements Comparator
{
public int compare(Object s1,Object s2)
{
String one = (String)s1;
String two = (String)s2;
/* for ascending order */
if(one.compareTo(two)>0){
return 1;
}else{
return -1;
}
}
}
實際輸出
Before Sorting Elements Are :[java, J-IV, A-V, J-V, J-IX, J-XX, J-X, J-I, J-II, datawarehouse, oracledba]
After Sorting Elements Are :[A-V, J-I, J-II, J-IV, J-IX, J-V, J-X, J-XX, datawarehouse, java, oracledba]
所需的輸出
Before Sorting Elements Are :[java, J-IV, A-V, J-V, J-IX, J-XX, J-X, J-I, J-II, datawarehouse, oracledba]
After Sorting Elements Are :[A-V, J-I, J-II, J-IV, J-V,J-IX, J-X, J-XX, datawarehouse, java, oracledba]
我應該使用正則表達式表達比較字符串。有些人可以告訴我解決方案
拍攝,我太慢,相同的鏈接... – Paul
我是一個新手標記,你可以解釋我的情況 –