異なる長さの単語列を指定します。この文字列を単語の長さの昇順にソートし、同じ長さのすべての単語を印刷した後に単語の長さを印刷しますか? 例:同じ長さのすべての単語を印刷した後に、単語の長さの昇順で文字列をソートし、単語の長さを印刷しますか?
INPUT:文字列S = OUTPUTを "なぜ私はあなたを雇う必要がある":私は1を、あなたが雇う3なぜ4が6
が
異なる長さの単語列を指定します。この文字列を単語の長さの昇順にソートし、同じ長さのすべての単語を印刷した後に単語の長さを印刷しますか? 例:同じ長さのすべての単語を印刷した後に、単語の長さの昇順で文字列をソートし、単語の長さを印刷しますか?
INPUT:文字列S = OUTPUTを "なぜ私はあなたを雇う必要がある":私は1を、あなたが雇う3なぜ4が6
が
気にいらないように、次のコードで私を助けてくださいする必要があります
import java.util.Arrays;
import java.util.Comparator;
public class sortStrings {
public static void main(String args[]){
String s = "Why should I hire you";
String[] s2 = s.split("\\s");
Arrays.sort(s2, new LengthComparator());
System.out.println(
s2[0]+" "+
s2[0].length()+" "+
s2[1]+" "+
s2[1].length()+" "+
s2[2]+" "+
s2[2].length()+" "+
s2[3]+" "+
s2[3].length()+" "+
s2[4]+" "+
s2[4].length()
);
}
}
class LengthComparator implements Comparator<String> {
//nulls first, then by increasing length,
// break ties using String's natural order
public int compare(String x, String y) {
if (x == null)
return y==null ? 0 : -1;
else if (y == null)
return +1;
else {
int lenx = x.length();
int leny = y.length();
if (lenx == leny)
return x.compareTo(y); //break ties?
else
return lenx < leny ? -1 : +1;
}
}
}
run:
I 1 Why 3 you 3 hire 4 should 6
BUILD SUCCESSFUL (total time: 0 seconds)
または(あなたがテンプレートと使いやすさでなら)あなたはTreeMapのを使用することができます。
String s = "Why should I hire you man";
String arr[] = s.split(" ");
TreeMap<Integer, String> sortedMap = new TreeMap<Integer, String>();
for (int i = 0; i < arr.length; i++){
if (sortedMap.containsKey(arr[i].length())){
String buff = sortedMap.get(arr[i].length());
sortedMap.put(arr[i].length(), buff.concat(" ").concat(arr[i]));
}
else
sortedMap.put(arr[i].length(), arr[i]);
}
Set<Entry<Integer, String>> set = sortedMap.entrySet();
Iterator<Entry<Integer, String>> it = set.iterator();
while(it.hasNext()) {
Map.Entry me = (Map.Entry)it.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Run :
1: I
3: Why you man
4: hire
6: should
ニースの解決策+1。 – c0der
これはあなたが学ぶ機会です。あなたが失敗したら、それを私たちに送ってください。そして私たちはあなたを助けます。 – SMA
このhttp://stackoverflow.com/help/how-to-askをお読みください。あなたがすでに試したことを示し、あなたの特定の問題を説明してください。 – Nikem
'' String.split( "") '、関連する' Comparator'を実装する 'TreeMap'、そしてループです。 – ifly6