无法替换Java字符串中的标点符号

时间:2014-06-11 00:39:24

标签: java android string replace

这是我的代码:

public void storeWords(String sentence)
{
    String[] wordlist = sentence.split("\\s+");

    int stringLength = wordlist.length;
    for(int j = 0; j < stringLength; j++)
    {
        wordlist[j].replaceAll("[^a-zA-Z ]", "");
        System.out.println(wordlist[j]);
    }
}

所以for循环现在只是检查每个单词是否替换了标点符号。没有。我还简单地检查过它&#34; sentence.replaceAll(.....)&#34;仍然没有工作。关于我出错的地方的任何线索?

"If somebody falls and has no protection, do they get hurt?"

返回

"If"
"somebody"
"falls"
"and"
"has"`
"no"
"protection, "
"do"
"they"
"get"
"hurt?"

2 个答案:

答案 0 :(得分:4)

字符串是不可变的,你必须这样做:

wordlist[j] = wordlist[j].replaceAll("[^a-zA-Z ]", "");

(immutable意味着一旦分配就无法更改它们,因此您需要进行新的赋值以更改String的值)

答案 1 :(得分:3)

当我将其更改为此时,您没有指定replaceAll()的结果 -

wordlist[j] = wordlist[j].replaceAll("[^a-zA-Z ]", "");

我得到输出(带输入)

If
somebody
falls
and
has
no
protection
do
they
get
hurt
  

注意来自Javadoc的返回是“结果字符串”。

相关问题