简体   繁体   English

格式化字符串的最快/最佳方法

[英]Quickest/Best way to Format a string

I know this may seem a junior question and it should have been easy to find the solution by Googling it but I am stuck. 我知道这看起来似乎是一个初级问题,通过谷歌搜索它应该很容易找到解决方案,但我被卡住了。

I am using C#. 我正在使用C#。

I have this string: 我有这个字符串:

20150824100112345 (for instance) 20150824100112345(例如)

I wish to transform it to a new string like so: 我希望将它转换为一个新的字符串,如下所示:

2015\\08\\24\\10\\00\\01\\12\\345 2015 \\ 08 \\ 24 \\ 10 \\ 00 \\ 01 \\ 12 \\ 345

Is there a '1-liner' of code I can use to accomplish this please? 我可以使用“1-liner”代码来实现这一目标吗?

NB Without 1st converting it to a datetime format NB没有第一次将其转换为日期时间格式

As said in the comments, you should really parse it to a DateTime and then turn that into a string. 如评论中所述,您应该将其解析为DateTime,然后将其转换为字符串。

But to parse a string as you asked you should use a Regex which can split it into groups. 但是要按照你的要求解析一个字符串,你应该使用一个可以将它分成组的正则表达式。

If you don't want to parse to DateTime first (ie if you don't care about validity) and if the input is always formatted as your example (zero-padded, so 08 instead of 8 ), you can do with a few simple Substring() calls: 如果您不想先解析DateTime(即如果您不关心有效性)并且输入始终被格式化为您的示例(零填充,那么08而不是8 ),您可以使用一些简单的Substring()调用:

string input = "20150824100112345";
string output = input.Substring(0, 4) + @"\" // 2015
              + input.Substring(4, 2) + @"\" // 08
              + input.Substring(6, 2) + @"\" // 24
              + input.Substring(8, 2) + @"\" // 10
              + input.Substring(10, 2) + @"\" // 01
              + input.Substring(12, 2) + @"\" // 12
              + input.Substring(14, 3); // 345

Or in Regex: 或者在Regex中:

string input = "20150824100112345";
string output = Regex.Replace(input, 
                  "([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{3})", 
                 @"$1\$2\$3\$4\$5\$6\$7");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将双精度格式转换为货币格式以C#输出字符串的最快/最佳方法是什么? - What's the quickest/best way to format a ?double to currency for string output in C#? 读取XML的最快/最佳方式 - Quickest/best way to read XML EF:按ID更新字段的最佳/最快方式 - EF: Best/Quickest way to update field by Id 在WinForms应用程序中显示List <String>的最快方法? - Quickest way to display a List<String> in a WinForms app? 从DataAdapter中的DateTime字段获取日期的最佳/最快方法 - Best/quickest way to get date from DateTime field in a DataAdapter 使用HttpResponseMessage获取图像的最佳/最快方法是什么 - What is the best/ quickest way to get an image using HttpResponseMessage 对命名空间中的所有表单覆盖Form Class方法的最佳/最快方法 - Best/Quickest way to override a Form Class method for all forms in namespace C#将字符串日期格式转换为另一个字符串的最佳方法? - C# Best way to convert string date format to another string? 将所有String元素从List连接到String的最快方法 - Quickest way to concatenate all String elements from List to String 通过字符串C#在很大的列表中搜索对象的最快方法 - Quickest way to search for objects in a very large list by string C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM