[英]Sort an array of strings based on length in ascending order
問題是按照字符串的長度升序打印字符串數組。
例如
input={"vellore","i","from","am"}
output=i am from vellore
這是我的代碼:
int n=sc.nextInt();
sc.nextLine();
String[] arr = new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLine();
}
//System.out.println(Arrays.toString(arr));
Arrays.sort(arr);
for(String i: arr){
System.out.print(i+" ");
}
現在我知道我的 output 將以“我來自我維洛爾”的詞匯順序出現,但我想使用排序方法獲得我想要的 output。 我嘗試使用 Collections.sort() 以及使用 arraylist 但我仍然沒有得到我想要的 output。
我想通過比較字符串和所有的長度來使用排序方法而不使用常規方法來獲取我的 output。
你想要一個Comparator
。 在這種情況下,您特別希望從比較String
長度開始。 我建議你然后自然地比較(打破關系)。 喜歡,
String[] arr = { "vellore", "i", "from", "am" };
Arrays.sort(arr, Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
System.out.println(Arrays.toString(arr));
輸出(按要求)
[i, am, from, vellore]
Comparator
.comparingLong( ( String s ) -> s.codePoints().count() )
.thenComparing( Comparator.naturalOrder() )
char
Frisch 的答案在建議使用Comparator
時是正確的。 但是,那里看到的方法參考String::length
對大多數字符都失敗了。 請參閱此示例。 String#length
方法將兩個字符的字符串(如c
)錯誤地報告為三個。
失敗是因為該方法依賴於自 Java 2 以來一直存在的char
。作為 16 位值, char
類型在物理上無法表示 Unicode 中定義的超過 140,000 個字符中的大部分。
相反,使用 Unicode 代碼點整數。
切換出該方法參考以使用代碼點而不是char
類型。
這里我們使用String#codePoints
來生成一個IntStream
。 該IntStream
是每個字符的代碼點編號的 stream,其值在零到略超過一百萬的范圍內。 然后我們使用IntStream#count
來獲取 stream 中的值的計數,即原始字符串中字符的計數。
String[] arr = { "a1", "c🕒", "b2", "d4" };
Arrays
.sort(
arr ,
Comparator
.comparingLong( ( String s ) -> s.codePoints().count() )
.thenComparing( Comparator.naturalOrder() )
);
System.out.println( Arrays.toString( arr ) );
[a1,b2,c,d4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.