我正在尝试编写一个程序来读取一串文本并打印本文中的所有数字及其频率。
输入示例:park car at the parking lot
对应输出:ar:3 pa:2 rk:2 at:1 ca:1 he:1 in:1 ki:1 lo:1 ng:1 ot:1 th:1
当我尝试此示例输入时,它会输出[ar:3, pa:2, rk:2, ca:1, at:1, th:1, he:1, ki:1, in:1, ng:1, lo:1, ot:1]
如何解决此问题,以便它不会有括号和逗号?
public class Digrams {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
ArrayList<String> repetition = new ArrayList<String>();
ArrayList<String> digrams = new ArrayList<String>();
String digram;
for (int i = 0; i < str.length() - 1; i++) {
digram = str.substring(i, i + 2);
if (repetition.contains(digram) || digram.contains(" ") || digram.length() < 2) {
continue;
}
int occurances = (str.length() - str.replace(digram, "").length()) / 2;
digrams.add(digram + ":" + occurances);
repetition.add(digram);
}
Collections.sort(digrams, (s1, s2) -> s2.substring(3, 4).compareTo(s1.substring(3, 4)));
System.out.println(digrams);
}
}
答案 0 :(得分:2)
不是最有效的解决方案,但它可以完成这项工作。
String result = digrams.toString();
System.out.println(result.replaceAll(",","").replace("[","").replace("]",""));
答案 1 :(得分:-1)
替换行
System.out.println(digrams);
带
System.out.println(String.join(" ", digrams));