从java中的String数组中删除所有非字母字符 [英] Remove all non alphabetic characters from a String array in java

查看:134
本文介绍了从java中的String数组中删除所有非字母字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个方法,从Java String [] 中删除​​所有非字母字符,然后将String转换为小写字符串。我已经尝试使用正则表达式来替换所有非字母字符的出现。但是,我得到的输出无法这样做。这是代码

I'm trying to write a method that removes all non alphabetic characters from a Java String[] and then convert the String to an lower case string. I've tried using regular expression to replace the occurence of all non alphabetic characters by "" .However, the output that I am getting is not able to do so. Here is the code

static String[] inputValidator(String[] line) {
    for(int i = 0; i < line.length; i++) {
       line[i].replaceAll("[^a-zA-Z]", "");
       line[i].toLowerCase();
    }
    return line;
}

但是,如果我尝试提供非字母输入(例如 - )输出也包含它们,因为它们不会被删除。

However if I try to supply an input that has non alphabets (say - or .) the output also consists of them, as they are not removed.

示例输入

A dog is an animal. Animals are not people.

我收到的输出

A
dog
is
an
animal.
Animals
are
not
people.

预期的输出

a
dog
is
an
animal
animals
are
not
people


推荐答案

问题是你的改变是没有存储,因为字符串是不可变的。每个方法调用返回一个新的 String 表示更改,当前 String 保持不变。您只需将返回的 String 存储回数组。

The problem is your changes are not being stored because Strings are immutable. Each of the method calls is returning a new String representing the change, with the current String staying the same. You just need to store the returned String back into the array.

line[i] = line[i].replaceAll("[^a-zA-Z]", "");
line[i] = line[i].toLowerCase();

因为每个方法都返回 String 你可以将方法调用链接在一起。这将对第一个结果执行第二个方法调用,允许您在一行中执行两个操作。

Because the each method is returning a String you can chain your method calls together. This will perform the second method call on the result of the first, allowing you to do both actions in one line.

line[i] = line[i].replaceAll("[^a-zA-Z]", "").toLowerCase();

这篇关于从java中的String数组中删除所有非字母字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆