Text cleaning and replacement: delete \n from a text in Java

后端 未结 9 1929
我在风中等你
我在风中等你 2020-12-08 19:57

I\'m cleaning an incoming text in my Java code. The text includes a lot of \"\\n\", but not as in a new line, but literally \"\\n\". I was using replaceAll() from the String

9条回答
  •  醉梦人生
    2020-12-08 20:37

    I believe replaceAll() is an expensive operation. The below solution will probably perform better:

    String temp = "Hi \n Wssup??";          
    System.out.println(temp);
    
    StringBuilder result = new StringBuilder();
    
    StringTokenizer t = new StringTokenizer(temp, "\n");
    
    while (t.hasMoreTokens()) {
        result.append(t.nextToken().trim()).append("");
    }
    String result_of_temp = result.toString();
    
    System.out.println(result_of_temp);
    

提交回复
热议问题