replace(“\ n”,“”)不起作用

时间:2014-12-02 22:04:08

标签: java string replace

String in = "dr. goldberg offers everything i look for in a general practitioner.  he's nice and easy to talk to without being patronizing; he's always on time in seeing his patients; he's affiliated with a top-notch hospital (nyu) which my parents have explained to me is very important in case something happens and you need surgery; and you can get referrals to see specialists without having to see him first.  really, what more do you need?  i'm sitting here trying to think of any complaint\n\ns i have about him, but i'm really drawing\n a blank.";

此代码似乎工作正常。

in = in.replaceAll("\n", "");

但是这个

for(String temp: review){
    String reviews = (StringUtils.substringBetween(temp,"\"text\": \"", "\", \"type\"")).replaceAll("\n", "");

    if(reviews.equals(in)){
        System.out.println("yes");
        System.exit(1);
    }
}

似乎不起作用。它不会删除新的行常数,有人可以解释原因!

(我使用substringBetween从文件中获取文本的一部分)

1 个答案:

答案 0 :(得分:0)

查看以下代码:

String sample="This string has new line \\n " + "New line is here if \\n \n is working";
    System.out.println("Original String: " + sample); //replacing \n or newline character so that all text come in one line 
    System.out.println("Escaped String: " + sample.replaceAll("\n", ""));

或者,您可以使用系统属性删除新行字符,如下所示:

String text = readFileAsString("words.txt"); 
text = text.replace(System.getProperty("line.separator"), "");