根据java中包含的数字字符对单词进行排序

时间:2013-08-25 09:34:30

标签: java string sorting

如何根据java中包含的数字字符对单词进行排序? e.g。

String Given : "my name is dhana"
O/p should be : "dhana name my is"

5 个答案:

答案 0 :(得分:2)

  • 选择string

  • split按空格(单词)

  • array转换为ArrayList

  • 以您希望的方式创建自定义comparatorsort(此处length

答案 1 :(得分:2)

使用此

  public void func()
        {
        String input =  "my name is dhana";
        String input_array[] = input.split(" ");
        Collections.sort(input_array, new CustomComparator());
        print_Array(input_array);
       }

<强> CustomComaparator.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);
    }
}

答案 2 :(得分:1)

您可以使用首先按长度进行比较的Comparator,如果长度相同,请使用String.compareTo()

答案 3 :(得分:0)

这是一种不需要创建自定义Comparator的替代方法。我建议只是为了完整。

  1. 用文字拆分字符串。
  2. 创建SortedMap。
  3. 迭代单词列表。
  4. 用“%03d%05d”填充它.format(999-aWord.length(),i) - &gt; aWord,其中i是单词列表中aWord的索引。这里的密钥是 xxxyyyyy 形式,其中 xxx 是字长的倒数(对于l = 1为998,对于l = 2为997等),因此排序如果从最长到最短, yyyyy 允许区分相同长度的单词(以及同一单词的多次出现)。
  5. 结果是map.values()。
  6. 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]
    

    ,这是正确的。事实上,相同大小的Stringinput中的位置列出。

答案 4 :(得分:0)

解决问题的方法可以是使用split上的正则表达式:

    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
<{1}}的

是:

System.out.println(descOrderedString)
相关问题