既然已知格式并且不应更改,那么使用子字符串就可以解决问题。
string data = "bsarbirthd0692";
string name, desc, date;
name = data.Substring(0, 4);
desc = data.Substring(4, 6);
date = data.SubString(10);
编辑
你还可以创建扩展方法来实现任何你想要的功能。这显然比之前的建议更复杂。
public static class StringExtension
{
public static string[] ParseFormat(this string str, params int[] obj)
{
int startIndex = 0;
string[] pieces = new string[obj.Length];
for (int i = 0; i < obj.Length; i++)
{
if (startIndex + obj[i] < str.Length)
{
pieces[i] = str.Substring(startIndex, obj[i]);
startIndex += obj[i];
}
else if (startIndex + obj[i] >= str.Length && startIndex < str.Length)
{
pieces[i] = str.Substring(startIndex);
startIndex += str.Length + startIndex;
}
}
return pieces;
}
}
使用方式 1:
string d = "bsarbirthd0692";
string[] pieces = d.ParseFormat(4,6,4);
结果:
用法2:
string d = "bsarbirthd0692";
string[] pieces = d.ParseFormat(4,6,4,1,2,3);
结果:
string.Format
提出逆函数建议。 - Stefan Hanke