java - 删除ArrayList中每个索引的前导空格

标签 java regex string arraylist java-8

所以,除了修剪功能之外,一切都工作正常。不知道好不好用。

实际上我正在使用ArrayList创建倒排索引。从文件中获取行,拆分为单词(标记化)并删除标点符号。当我到达删除停用词的部分时,它与文件中提供的停用词不匹配。我认为这是因为ArrayList的每个索引的前导空格。

停用词列表:

a, is, the, of, all, and, to, can, be, as, once, for, at, am, are, has, have, had, up, his, her, in, on, no, we, do

我的策略:

String [] TempArray = new String[word.size()];

for (int i = 0; i < word.size(); i++) {
    word.set(i, word.get(i).toLowerCase());
    word.set(i, word.get(i).replaceAll("[^a-zA-Z]", ""));
}   

for (int i = 0; i < word.size(); i++) {
    TempArray[i] = word.get(i);
    TempArray[i] = TempArray[i].trim();
    word.set(i, TempArray[i]);
    System.out.println(word.get(i));
}

输出:

[a, blunder, by, anton, chekhov, , an, illustration, for, the, story, a, blunder, by, the, author, anton, chekhov, portrait, of, ivan, lazhechnikov...]

如有任何建议,我们将不胜感激!

最佳答案

怎么样:

Arrays.stream(TempArray)
    .filter(s -> s != null)
    .map(String::trim)
    .toArray(String[]::new);

这将创建没有前导或尾随空格的新数组。

关于java - 删除ArrayList中每个索引的前导空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55109034/

相关文章:

Mysql在文本中查找关键字

java - 为什么会在jsf文件中显示空指针异常?

java - 如何将变量的数据与 ArrayList 中的数据进行比较?

C# Regex.Replace() 吞下原始字符串的一部分

regex - 如何检查一个字符串是否完全匹配 Scala 中的正则表达式?

java - Java 中的正则表达式——只返回最后一个匹配项

java - Dropwizard - 绑定(bind)不匹配 : not a valid substitute for the bounded parameter

java - 在不影响布局大小的情况下在Linearlayout上设置背景png

regex - 忽略文件夹中的文件夹

python - python 中 string.partition 的良好实践