在打印所有相同长度的单词后,按字长的升序排序字符串并打印单词的长度?

时间:2016-07-03 06:46:04

标签: java string

给出一串不同长度的单词。在打印所有相同长度的单词后,按字长和字的打印长度的升序排序此字符串? 示例:

INPUT:String s =“我为什么要雇用你” 输出:I 1为什么你3雇用4应该6

请在以下代码中帮助我

2 个答案:

答案 0 :(得分:1)

或者你可以使用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 :(得分:0)

像:

 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)