简体   繁体   English

Java替换字符串中的特殊字符

[英]Java replace special characters in a string

I have a string like this: 我有一个像这样的字符串:

BEGIN\n\n\n\nTHIS IS A STRING\n\nEND

And I want to remove all the new line characters and have the result as : 我想删除所有换行符,结果为:

BEGIN THIS IS A STRING END

How do i accomplish this? 我该如何完成? The standard API functions will not work because of the escape sequence in my experience. 由于我的经验,标准的API函数将无法正常运行,这是因为转义序列。

Try str.replaceAll("\\\\\\\\n", ""); 尝试str.replaceAll("\\\\\\\\n", ""); - this is called double escaping :) -这称为两次转义:)

A simple replace('\\n', ' ') will cause the string to become: 一个简单的replace('\\n', ' ')将使字符串变为:

 BEGIN    THIS IS A STRING  END
      ****                **

where the * 's are spaces. *是空格。 If you want single spaces, try replaceAll("[\\r\\n]{2,}", " ") 如果要使用单个空格,请尝试replaceAll("[\\r\\n]{2,}", " ")

And in case they're no line breaks but literal "\\n" 's wither try: 并且在没有换行符的情况下,请尝试使用文字"\\n"

replace("\\n", " ")

or: 要么:

replaceAll("(\\\\n){2,}", " ")
String str = "BEGIN\n\n\n\nTHIS IS A STRING\n\nEND;";

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

// Remove extra white spaces
while (str.indexOf("  ") > 0) {
   str = str.replaceAll("  ", " ");
}

This works for me: 这对我有用:

String s = "BEGIN\n\n\n\nTHIS IS A STRING\n\nEND";
String t = s.replaceAll("[\n]+", " ");
System.out.println(t);

The key is the reg-ex. 关键是reg-ex。

当然,标准API可以使用,但是您可能必须进行两次转义(“ \\\\ n”)。

I don't usually code in Java, but a quick search leads me to believe that String.trim should work for you. 我通常不使用Java编写代码,但是快速搜索使我相信String.trim应该适合您。 It says that it removes leading and trailing white space along with \\n \\t etc... 它说它删除了\\ n \\ t等开头和结尾的空格...

Hope this snippet will help, 希望这段代码对您有所帮助,

Scanner sc = new Scanner(new StringReader("BEGIN\n\n\n\nTHIS IS A STRING\n\nEND "));
    String out = "";
    while (sc.hasNext()) {
        out += sc.next() + " ";
    }
    System.out.println(out);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM