有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

无法删除java字符串中的换行符(\n)。有可能吗?

基本上,我要做的就是从Java中的字符串中删除换行符。我看过几十篇提出类似问题的帖子,它们都说了同样的话,但似乎没有一篇适合我。以下是所有代码,我有三行代码:

    String text = "\\n          texttexttext     \\n";
    text = text.replaceAll("\\n", "");
    System.out.println(text);

这个字符串与我实际尝试使用的字符串类似,但即使使用这个字符串,我也无法找到换行符并替换它。替补队员就是看不到,我也不知道为什么

我也尝试过很多其他的事情,比如

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

或者

    text = text.replaceAll("\\r\\n|\\r|\\n", " ");

但什么也找不到这个角色。我甚至无法使用Regex模式和Matcher对象找到它。我正在做的唯一一件稍微不寻常的事情是在Junit测试bean中进行,但我不敢相信这会起到任何作用


共 (4) 个答案

  1. # 1 楼答案

    String newLine = System.getProperty("line.separator")
    System.out.println(newLine.contains("\n")); // this is a new line
    System.out.println(newLine.contains("\\n"));
    

    输出:

    true
    false
    
  2. # 2 楼答案

    您的原始text中没有换行符。您转义了反斜杠,而不是n,因此text字符串中有实际的反斜杠\n字符

    必须在正则表达式中转义反斜杠字符,但不能在文本字符串中转义

    如果将text初始化为"\n texttexttext \n",那么它将按预期查找并替换这些换行符

  3. # 3 楼答案

    如果head = 'Hello'但是当你print(head)->'Hello\n' 您可以通过rstrip()remove()删除\n

    你可以用我的密码

    **head=a[0:(len(head)-1)]**
    

    删除隐藏在字符串中的\n

    (在py 3上测试) 祝你好运

  4. # 4 楼答案

    除了@rgetman的答案,为了让它对社区有用,下面是一个很棒的Java程序(有关更多信息,您可以从here阅读整篇文章)这将取代新线字符

    public class StringReplaceTask{
    
    
        public static void main(String args[]) {
    
            // Removing new line characters form Java String
            String sample="We are going to replace newline character \\n "
                    + "New line should start now 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", ""));
    
    
            // removing line breaks from String read from text file in Java
            String text = readFileAsString("words.txt");
            text = text.replace(System.getProperty("line.separator"), "");
    
        }