Berserker
Berserker

Reputation: 15

String Manipulation C# - BreakLine in Text

I need a help with my code, I'm trying to format a text in a string setting breaklines before the dates formats.

Example:

string formulario = "21/02/2011 - 15:02 - Albert Einsten - Won the lottery 21/11/2012 - 16:14 - Nicollas Tesla - Lost his keys. Keys Id: 0666793 ";

I need my string to be in the next format:

21/02/2011 - 15:02 - Albert Einsten - Won the lottery

21/11/2012 - 16:14 - Nicollas Tesla - Lost his keys. Keys Id: 0666793

Upvotes: 0

Views: 166

Answers (4)

ataraxia
ataraxia

Reputation: 1181

You need to use a line break \n or even better System.Environment.NewLine

Upvotes: 1

Berserker
Berserker

Reputation: 15

I found a Solution using Regex

String pattern  = @" ([\d]{2}/[\d]{2}/[\d]{4})";
String Formulario = "21/02/2011 - 15:02 - Albert Einsten - Won the lottery 21/11/2012 - 16:14 - Nicollas Tesla - Lost his keys. Keys Id: 0666793 ";

formulario = Regex.Replace(formulario, pattern, Environment.NewLine + "$&");

Console.WriteLine(formulario.Replace("\n ", "\n"));

Upvotes: 0

Liam
Liam

Reputation: 29694

Just use a verbatim string:

string formulario = @"21/02/2011 - 15:02 - Albert Einsten - Won the lottery 

21/11/2012 - 16:14 - Nicollas Tesla - Lost his keys. Keys Id: 0666793";

Or format your string using Environment.NewLine:

//string.Format will replace {0} with the result of Environment.NewLine
string formulario = string.Format("21/02/2011 - 15:02 - Albert Einsten - Won the lottery{0}{0}21/11/2012 - 16:14 - Nicollas Tesla - Lost his keys. Keys Id: 0666793", Environment.NewLine);

Or you can use C# 6 $ strings (shorthand for the above)

string formulario = $"21/02/2011 - 15:02 - Albert Einsten - Won the lottery{Environment.NewLine}{Environment.NewLine}21/11/2012 - 16:14 - Nicollas Tesla - Lost his keys. Keys Id: 0666793";

Upvotes: 0

Liquid Core
Liquid Core

Reputation: 1

Environment.NewLine is your friend. It's accurate for every environment as the framework chooses the appropriate line ending automatically and you can assign it to a string to use it in a faster way if you don't like its verbosity.

Like

string nl = Environment.NewLine;
string phrase = "now we go to a new line" + nl;

or if you use C# 6 at least you can use syntactic sugar with string interpolation:

 string nl = Environment.NewLine;
 string phrase2 = $"now we go to a new line{nl}And this is the new line{nl}And this is another one";

(or put Environment.NewLine directly inside brackets if you don't like the variable)

Upvotes: 0

Related Questions