题目:分析以下需求,并用代码实现:
(1)统计每个单词出现的次数
(2)有如下字符串"If you want to change your fate I think you must come to the ujiuye to learn java"(用空格间隔)
(3)打印格式:
to=3
think=1
you=2
方法一: 运用for循环嵌套解决
public class Csdn {
public static void main(String[] args) {
String str = "If you want to change your fate I think you must come to the ujiuye to learn java";
String[] st = str.split(" ");
for(int i = 0;i < st.length;i++){
int count = 0;
for(int j = i;j >= 0;j--){ //避免重复输出相同单词的次数
if(st[i].equals(st[j])){
count++;
}
}
if(count != 1){
continue;
}else{
count = 0;
for(String s:st){
if(st[i].equals(s))
count++;
}
System.out.println(st[i]+"="+count);
}
}
}
}
方法二: 运用Map解决
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class Csdn{
public static void main(String[] args) {
String str = "If you want to change your fate I think you must come to the ujiuye to learn java";
String[] st = str.split(" ");
Map<String,Integer> map = new LinkedHashMap<>(); //获取键值对
for(String s:st){
boolean flag = map.containsKey(s); //map中是否包含s键
int count = 0;
if(flag){
count = map.get(s); //根据s键获取值,将值付给count
}
map.put(s, ++count); //存入键值对
}
Set<String> set = map.keySet(); //获取键的集合
for(String s:set){
System.out.println(s+"="+map.get(s));
}
}
}
愿前程似锦