String Manipulation C# - 文本中的BreakLine

时间:2018-06-06 15:01:21

标签: c#

我需要帮助我的代码,我正在尝试在日期格式之前格式化字符串设置分隔线中的文本。

示例:

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 ";

我需要我的字符串采用下一种格式:

  

21/02/2011 - 15:02 - Albert Einsten - 赢了彩票

     

21/11/2012 - 16:14 - 尼古拉斯特斯拉 - 失去了他的钥匙。钥匙ID:0666793

4 个答案:

答案 0 :(得分:1)

您需要使用换行符\n或更好System.Environment.NewLine

答案 1 :(得分:0)

只需使用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";

或使用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);

或者您可以使用C#6 $字符串(上述简写)

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";

答案 2 :(得分:0)

Environment.NewLine是你的朋友。 它对于每个环境都是准确的,因为框架会自动选择适当的行结束,如果你不喜欢它的详细程度,你可以将它分配给一个字符串以更快的方式使用它。

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

或者如果你至少使用C#6,你可以使用带有字符串插值的语法糖:

 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";

(如果您不喜欢变量,请将Environment.NewLine直接放在括号内)

答案 3 :(得分:0)

我找到了使用正则表达式的解决方案

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"));