首页 > 解决方案 > 使用全局变量的字符串到字符串数组转换

问题描述

我对java有以下问题。Class中的这个方法应该按原样返回String

private String getAsString(Resource res) {

        return "We wish you good luck in this exam!\nWe hope you are well pre-\npared.";
    }

然后在构造函数中这个字符串被转换成单词数组

private int index;
private String string_arr[];

public TextFileIterator(Resource res) {
    this.index=0;
    if(res==null){
        throw new NullPointerException();
    }
    String text=this.getAsString(res);
    //text=text.replaceAll("-\n(?=[a-z])", "");
    text=text.replaceAll("\\n", "");
    text=text.replaceAll("!", " ");
    text=text.replaceAll("-", "");
    text=text.replaceAll(".", "");
    this.string_arr=text.split(" ");

}

问题是最后我得到的数组是空的......有什么问题。我附上调试器屏幕截图。 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

请解释一下为什么会这样?

标签: javaarrays

解决方案


罪魁祸首是第17行-

text=text.replaceAll(".", "");

上面的行是用“”替换所有内容,因为在正则表达式世界中“。” 表示任何字符。

试试这个——

text=text.replaceAll("\\.", "");

推荐阅读