如何根据java中包含的数字字符对单词进行排序?例如
String Given : "my name is dhana"
O/p should be : "dhana name my is"
拿一个string
split
它按空格(成词)
转换array
成ArrayList
comparator
以您想要的方式创建自定义sort
(此处由length
)
用这个
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);
}
}
您可以使用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
相同大小的 s 是按位置列出的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