代码之家  ›  专栏  ›  技术社区  ›  user764754

防止多行原始字符串文字中出现新行字符

  •  1
  • user764754  · 技术社区  · 7 月前

    我如何定义原始字符串文字,其中代码中的换行符只是为了可读性,没有新行字符( \r , \n )在结果字符串中?

    大致如下:

    string str =
        """
        first line;
        also first line
        """;
    

    应导致 "first line;also first line" .

    到目前为止,这是我想出来的,但它相当丑陋:

    str =
        $"""
        first line;{""
        }also first line
        """;
    

    至少它比以下内容稍微简洁一些:

    str =
        """
        first line;
        """ +
        """
        also first line
        """;
    

    一位受欢迎的法学硕士告诉我,在C#中,我可以使用 \ 在原始字符串文字的行末尾,以防止新行字符,但这似乎不起作用,因为反斜杠只是按字面意思处理。

    1 回复  |  直到 7 月前
        1
  •  1
  •   Anton Komyshan    7 月前
    public static class StringExtensions
    {
        public static string WithoutNewlines(this string input)
        {
            return input.Replace("\n", "").Replace("\r", "");
        }
    }
    
    public static void Main()
    {
        string str =
        """
        first line;
        also first line
        """.WithoutNewlines();
        
        Console.WriteLine(str);
    }
    
    推荐文章