【问题标题】:replace("\n", "") is not working [duplicate]替换(“\n”,“”)不起作用[重复]
【发布时间】:2014-12-02 22:04:07
【问题描述】:
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 从文件中获取部分文本)

【问题讨论】:

  • StringUtils.substringBetween(temp,"\"text\": \"", "\", \"type\"")) 在运行时评估什么?
  • @JigarJoshi - 它评估为与 input2 相同的字符串,但使用新行常量,替换似乎不起作用
  • 我也在检查这两个字符串的相等性,使用 input.equals(reviews),它应该评估为 true,但事实并非如此。
  • 另请注意,您使用的是replace() 而不是replaceAll(),因此它不会替换所有但首先
  • @RuslanOstafiychuk - 我试过了,但还是不行。

标签: java string replace


【解决方案1】:

看看下面的代码:

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

【讨论】:

    猜你喜欢
    • 2018-07-31
    • 2010-12-25
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    相关资源
    最近更新 更多