是否有任何函数将数字字符串格式化为另一个字符串? [英] Is there any function to format a numeric string to another string ?
本文介绍了是否有任何函数将数字字符串格式化为另一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:1995/3/4到1995/03/04
我试过这段代码,但我认为如果有更简单的方法会更好
for example:"1995/3/4" to "1995/03/04"
I tried this code but I think it's better if there was an easier way
string _date=:"1995/3/4"
string[] s=_date.Split('/');
_date=s[0]+"/"+Convert.toInt32(s[1]).ToString("00")+"/"+Convert.toInt32(s[2]).ToString("00");
推荐答案
您可以使用正则表达式。
首先,将其添加到代码文件的顶部:
You can use a regular expression for this.
First, add this at the top of your code file:
using System.Text.RegularExpressions;
然后,使用此代码:
Then, use this code:
_date = Regex.Replace(_date, @"/(?!\d{2,})", "/0");
T他用 / 0
(斜线和零)代替每个斜线,后面跟不是2位或更多位。
This replaces every slash, that's not followed by 2 or more digits, with /0
(a slash and a zero).
< b>如果这些总是日期字符串,我会解析日期,然后重新转换为格式化字符串:
If these are always date strings, I would parse the date and then re-convert to a formatted string:
//At the top:
using System.Globalization;
//
// Assuming this is Year/Month/Day in the format strings below.
// Adjustment for otherwise is pretty obvious.
string _date=:"1995/3/4";
DateTime rawDate;
if (DateTime.TryParseExact(_date, "yyyy/M/d", CultureInfo.InvariantCulture, DateTimeStyles.None, out rawDate))
{
_date = rawDate.ToString(CultureInfo.InvariantCulture, "yyyy/MM/dd");
}
else
{
// _date string was not a valid date. Handle "appropriately"
}
为我的应用程序使用适当的 CultureInfo
上面有 CultureInfo.InvariantCulture
。
这篇关于是否有任何函数将数字字符串格式化为另一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文