简体   繁体   English

格式化数字字符串的最简单方法是什么?

[英]What's the easiest way to format a numeric string?

I have the following string: "12345678901", and I want it to be formatted as "123.456.789-01", I'm currently doing it like this:我有以下字符串:“12345678901”,我希望它的格式为“123.456.789-01”,我目前正在这样做:

string s = "12345678901";
string formatted = Int64.Parse(s).ToString("000.000.000-00"); // = "123.456.789-01"

Is there a better way of doing this, can I do this directly, without having to convert the string to int and back to string again?有没有更好的方法来做到这一点,我可以直接做到这一点,而不必将字符串转换为 int 并再次转换回字符串?

Yes, you can reach your result without conversion to an integer and reformatting the integer to a string and it is even faster.是的,您可以在不转换为整数并将整数重新格式化为字符串的情况下获得结果,而且速度更快。

s = "12345678901";
StringBuilder sb = new StringBuilder(s);
int pos = s.Length - 2;
if (pos > 0) sb.Insert(pos, "-");
pos -= 3;
while (pos > 0)
{
    sb.Insert(pos, ".");
    pos -= 3;
}
string formatted = sb.ToString();

This is more or less what madrereflection has told you in comments with the only difference that the example here uses StringBuilder to avoid the continuous rebuild of the string.这或多或少是 madrereflection 在评论中告诉你的,唯一的区别是这里的示例使用 StringBuilder 来避免字符串的连续重建。 From simple benchmark it is three times faster than the current approach but of course more code is required.从简单的基准测试来看,它比当前的方法快三倍,但当然需要更多的代码。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM