字符串到字符串数组的转换与全局变量。

huangapple go评论63阅读模式
英文:

String to String array conversion with global variables

问题

以下是您提供的内容的翻译:

我在使用Java时遇到了以下问题。在类中,这个方法应该原样返回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(" ");
}

问题是,最后我得到了一个为空的数组...问题出在哪里。我附上了调试器的截图。

字符串到字符串数组的转换与全局变量。
字符串到字符串数组的转换与全局变量。
字符串到字符串数组的转换与全局变量。
字符串到字符串数组的转换与全局变量。

请问您能解释一下为什么会发生这种情况吗?

英文:

I have following problem with java.This method in Class should return String as is.

private String getAsString(Resource res) {

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

Then in Constructor this String shlud be converted into array of words

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(" ");

}

Problem is that at the end I get array which is null... what is the problem. I attach the debugger screenshots.
字符串到字符串数组的转换与全局变量。
字符串到字符串数组的转换与全局变量。
字符串到字符串数组的转换与全局变量。
字符串到字符串数组的转换与全局变量。

Please could explain me why does it happen?

答案1

得分: 3

罪魁祸首是第17行-

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

上述行将所有内容替换为"",因为在正则表达式世界中,"."代表任意字符。

请尝试改用以下方式-

text=text.replaceAll("\\。", "");
英文:

The culprit is line no 17-

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

The above line is replacing all of the content with "", because in regex world "." means any character.

Try this instead-

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

huangapple
  • 本文由 发表于 2020年8月30日 02:13:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63650309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定