package 字符串;
import java.util.Scanner;
public class SDF {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] strings = new String[n];
for(int i= 0;i<strings.length;i++) {
strings[i]=sc.next();
}
for(int i=0;i<strings.length;i++) {
int count=0;
for(int j=0;j<strings.length;j++) {
if(strings[i].equals(strings[j])) {
count++;
}
}
System.out.println(strings[i]+count);
}
sc.close();
}
}
假设我们有一个字符串 text 包含一个或多个单词,它们由空格分隔。下面是用Java编写的一段代码,可以输出每个独特单词及其出现次数:
import java.util.HashMap;
import java.util.Map;
public class WordCounter {
public static void main(String[] args) {
String text = "apple banana apple cherry banana";
Map<String, Integer> wordCounts = new HashMap<>();
// Split the text into words and count each occurrence of a word.
String[] words = text.split(" ");
for (String word : words) {
if (wordCounts.containsKey(word)) {
wordCounts.put(word, wordCounts.get(word) + 1);
} else {
wordCounts.put(word, 1);
}
}
// Print each unique word and its count.
for (String word : wordCounts.keySet()) {
System.out.println(word + ": " + wordCounts.get(word));
}
}
}
这里使用了 HashMap 来记录每个单词出现的次数。在遍历文本中的每个单词时,使用 containsKey() 方法检查单词是否已经存在于 wordCounts 映射中。如果是,则将其计数器加1;否则,将其添加到 wordCounts 中,并将其计数器初始化为1。 最后,遍历 wordCounts 并打印每个唯一单词和其出现次数。
题主可自行测试一下,忘采纳哦
用HashTable<string, int>字典代替string数组,HT的key是单词,value是出现的次数