简体   繁体   English

如何通过检查长度并比较Java中的文本来从数组中删除String?

[英]How to remove String from an array by checking length and comparing text in Java?

How to remove String from an array by checking length and comparing text in Java? 如何通过检查长度并比较Java中的文本来从数组中删除String?

Suppose user search for "Hi Tonki with Monkey" 假设用户搜索“ Hi Tonki with Monkey”

String[] pattern = userSearchString.toLowerCase().split("\\s");

1) We want to remove "With" from pattern and 1)我们要从模式和

2) also want to remove pattern with less then 3 size like "Hi". 2)还希望删除尺寸小于3的图案,例如“ Hi”。

So pattern should contain Tonki and Monkey only. 因此模式应仅包含Tonki和Monkey。

It will be fuitful if anyone can suggest method from Apache Commons or Guava. 如果有人可以从Apache Commons或Guava建议方法,那将是很幸运的。

Using Java 1.6 使用Java 1.6

A Java 8 solution would be to Stream the array and filter only the elements that you want, and collect it back into an array: Java 8解决方案是Stream处理数组并仅过滤所需的元素,然后将其收集回数组中:

Arrays.stream(pattern)
      .filter(word -> !word.equals("with"))
      .filter(word -> word.length() >= 3)
      .toArray(String[]::new);

A pre-Java 8 solution would be to filter the array manually. Java 8之前的解决方案是手动过滤数组。 However, we'll have to create a new array; 但是,我们必须创建一个新的数组。 but because we do not know the size of the new array in advance, we can use a List<String> and collect it to an array after adding its respective elements: 但是由于我们不预先知道新数组的大小,因此可以使用List<String>并在添加其各自的元素后将其收集到数组中:

List<String> list = new ArrayList<>();

for (String word : pattern) {
    if (word.length() < 3 || word.equals("with")) {
        continue;
    }

    list.add(word);
}

list.toArray(new String[list.size()]);

There's no need to use external libraries if they aren't required! 如果不需要外部库,则无需使用它们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM