Concrete way to output strings in C #

In C ++, I can do this:

cout << "Line 1\nLine 2\n";

In Java, I can do this:

System.out.printf("Line 1%nLine 2%n");

In C #, I really need to do one of these bulky things:

Console.WriteLine("Line 1");
Console.WriteLine("Line 2");

or

Console.Write("Line 1{0}Line 2{0}", Environment.NewLine);

or is there a more concise way that is platform independent?

+5
source share
7 answers

You can create an extension method for Environment.NewLine

public static class StringExtensions()
{
    public static string ToNL(this string item)
    {
        return item += Environment.NewLine;
    }
}

Now you can use NL(selected because of brevity)

Console.Write("Hello".NL());
Console.Write("World".NL());

writes out:

Hello
World

You can also create an extension method that simply writes something to the console.

public static void cout(this string item)
{
    Console.WriteLine(item);
    //Or Console.Write(item + Environment.NewLine);

}

And then:

"Hello".cout();
+4
source

This should work:

Console.Write("Line 1\r\nLine 2");
+3
source

?

Console.Write("Line 1\nLine2");

\r\n.

+2

Windows Environment.NewLine "\ r\n". ,

Console.Write("Line 1\r\nLine 2\r\n");

Console.Write("Line 1\nLine 2\n");

. Environment.NewLine , .

+2

Console, , . ConsoleHelper:

public static class ConsoleHelper
{
    public static void EnvironmentSafeWrite(string s)
    {
        s = Environment.NewLine == "\n" ? s : s.Replace("\n", Environment.NewLine);
        Console.Write(s);
    }
}

:

ConsoleHelper.EnvironmentSafeWrite("Line 1\nLine 2\n");
+2

Console.WriteLine() , .

NewLine, Console.Out.NewLine = "your string here";

+1

\r\nIt can be used on Windows platforms. However, you are not asking what platform you are targeting. If you want your code to be multi-platform and future, it's probably safer to useEnvironment.NewLine

0
source

All Articles