[英]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.