Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prevent new-line characters in a multiline raw string literal

How can I define raw string literal where the line breaks in the code are just for readability and there are no new-line characters (\r, \n) in the resulting string?

Something like this:

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

should result in "first line;also first line".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So far this is what I’ve come up with, but it’s pretty ugly:

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

At least it’s a bit less verbose than:

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

A popular LLM told me that in C# I can just use \ at the very end of a line in a raw string literal in order to prevent new-line characters, but that doesn’t seem to work because the backslash just gets treated literally.

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading