Javaに含まれる文字数に基づいて単語をソートする方法は?? 例えば
String Given : "my name is dhana"
O/p should be : "dhana name my is"
これを使って
public void func()
{
String input = "my name is dhana";
String input_array[] = input.split(" ");
Collections.sort(input_array, new CustomComparator());
print_Array(input_array);
}
CustomComparator.java
public class CustomComparator implements Comparator<String>
{
public int compare(String a, String b) {
if (a.length() > b.length()) {
return -1;
} else if (a.length() < b.length()) {
return 1;
}
return a.compareTo(b);
}
}
取るstring
split
それをスペースで(言葉に)
array
に変換ArrayList
好きなようにカスタムcomparator
を作成しsort
ます(ここではlength
)
最初に長さで比較するComparatorを使用でき、長さが同じ場合はString.compareTo()
.
これは、カスタム を作成する必要のない代替手段ですComparator
。完全を期すためにのみ提案しています。
String input= "This is a string with differently sized words. This is another sentence." ;
String[] splitInput= input.split("[ .]") ;
TreeMap<String,String> theMap= new TreeMap<String,String>() ;
int index= 0 ;
for(String word: splitInput ) {
if( word.length() > 0 ) {
String key= String.format("%03d%05d",(999-word.length()),index) ;
theMap.put(key,word);
index++;
}
}
System.out.println(theMap.values());
出力を生成します:
[differently, sentence, another, string, sized, words, This, with, This, is, is, a]
、 どちらが正しい。実際、String
同じサイズの は位置別にリストされていinput
ます。
問題の解決策は、分割時に正規表現を使用することです。
String str = "my name is dhana";
List<String> items = Arrays.asList(str.split("\\s+"));
print(items);
Collections.sort(items, new Comparator<String>() {
@Override
public int compare(String s0, String s1) {
// Descending order
if (s0.length() < s1.length())
return 1;
else if (s0.length() > s1.length())
return -1;
return 0;
}
});
String descOrderedString = "";
for (String item : items) {
descOrderedString += item + " ";
}
System.out.println(descOrderedString);
メソッドprint()
は次のようになります。
public void print(List<String> list) {
for(String s: list){
System.out.println(s);
}
}
出力:
はprint(items)
次のとおりです。
my
name
is
dhana
は次のSystem.out.println(descOrderedString)
とおりです。
dhana name my is