新人java编程题,来帮助一下。 10
java写一段代码,在下列文本中打印出包含单词”your”的句子(不区分大小写),并且按照出现次数从高到低排序。Makeyourselfathome.Noneofyour...
java 写一段代码,在下列文本中打印出包含单词”your”的句子(不区分大小写),并且按照出现次数从高到低排序。
Make yourself at home.
None of your business.
I will be more careful.
How about going to a move?
your life is your Own affair. 展开
Make yourself at home.
None of your business.
I will be more careful.
How about going to a move?
your life is your Own affair. 展开
2015-03-21
展开全部
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringRegexTest {
public static void main(String[] args) {
String[] strArr = {"Make yourself at home.",
"None of your business.",
"I will be more careful.",
"How about going to a move?",
"your life is your Own affair."};
Pattern pattern = Pattern.compile(".*?(your).*?", Pattern.CASE_INSENSITIVE);
List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
for(String str : strArr){
Matcher matcher = pattern.matcher(str);
int num = 0;
while (matcher.find()) {
num++;
}
Map<String,Object> map = new HashMap<String,Object>();
map.put("str", str);
map.put("num", num);
resultList.add(map);
}
Collections.sort(resultList, new Comparator<Map<String,Object>>() {
@Override
public int compare(Map<String,Object> m1, Map<String,Object> m2) {
int num1 = Integer.valueOf(m1.get("num").toString());
int num2 = Integer.valueOf(m2.get("num").toString());
return num2-num1;
}
});
for(Map<String,Object> map : resultList){
System.out.println("出现次数:"+map.get("num").toString()
+ ", 原字符串:" + map.get("str").toString());
}
}
}
输出结果如下:
出现次数:2, 原字符串:your life is your Own affair.
出现次数:1, 原字符串:Make yourself at home.
出现次数:1, 原字符串:None of your business.
出现次数:0, 原字符串:I will be more careful.
出现次数:0, 原字符串:How about going to a move?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询