java - 删除数组中的重复单词句子
问题描述
给定一个确定单词输出、每个单词长度和单词重复次数的问题,我有以下代码能够确定下面每个单词的单词和长度:
String sentence;
String charSentence;
String[] wordOutput;
private void analyzeWords(String s) {
String[] words = sentence.split(" ");
wordOutput = new String[words.length];
int[] repeats = new int[words.length];
// Increment a single repeat
for (int i = 0; i < words.length; i++) {
repeats[i] = 1;
// Increment when repeated.
for (int j = i + 1; j < words.length - 1; j++) {
if (words[i].equalsIgnoreCase(words[j])) {
repeats[i]++;
}
}
wordOutput[i] = words[i] + "\t" + words[i].length() + "\t" + repeats[i];
}
当我运行程序时,我得到以下输出:
Equal 5 2
Equal 5 1 <- This is a duplicate word and should not be here when it repeats.
有谁知道我的问题在哪里?与我的重复数组有关的东西吗?
解决方案
第一个问题是,在内部 for 循环中,您从i+1
to循环length-1
。您需要循环直到length
. 其次,您需要确定在 中是否出现任何单词,String
如果出现,请使用continue
语句。你可以做:
outer:
for (int i = 0; i < words.length; i++) {
repeats[i] = 1;
for(int index = i-1; index >= 0; index--) {
if(words[i].equals(words[index])) {
continue outer;
}
}
...
}
null
但是,这样做的问题是列表末尾会有值,因为您指定的Array
长度与单词数相同。要解决此问题,您可以执行以下操作:
wordOutput = Arrays.stream(wordOutput).filter(e-> e!= null).toArray(String[]::new);
这将过滤掉null
值
输出:
(输入String
:)"This is a String is a with a lot lot of this repeats repeats"
This 4 2
is 2 2
a 1 3
String 6 1
with 4 1
lot 3 2
of 2 1
this 4 1
repeats 7 2
推荐阅读
- android - 启用 Dotfuscator 社区版后,适用于 Android 的 Xamarin 表单应用程序崩溃
- javascript - 如果在垫步进器之前打开任何文档,如何禁用/停止 HostListener?
- django - 如何获取 Django 模板中两个日期时间字段之间的秒数差异?
- google-cloud-platform - 使用 terraform 设置 iam 权限时,保护自己免于失去对存储桶的访问权限?
- linux - “/bin/exec -c --”是什么意思?
- android - 如何在初始登录时自动将用户添加到 Firebase 中的现有节点
- python - Django 信号没有收到任何信号(不起作用)
- authentication - Google 登录 - 访问令牌、身份验证令牌和 JWT ID 令牌之间的区别
- android - android 中的 Media Recorder API 生成无法播放的文件
- typescript - 在 Typescript 中有一个静态创建方法而不是构造函数吗?