String Format Does Not Works For string

会有一股神秘感。 提交于 2019-12-11 06:01:29

问题


I have a serial number which is String type.

Like This;

String.Format("{0:####-####-####-####}", "1234567891234567" );

I need to see Like This, 1234-5678-9123-4567;

Bu this Code does not work?

Can you help me?


回答1:


That syntax takes an int, try this:

String.Format("{0:####-####-####-####}", 1234567891234567);

Edit: If you want to use this syntax on a string try this:

String.Format("{0:####-####-####-####}", Convert.ToInt64("1234567891234567"))



回答2:


For ####-####-####-####, you will need a number. But you're feeding it a string.

It would be more practical to pad the string with additional zero's on the left so it becomes exactly 16 characters. Then insert the dash in three locations inside the string. Converting it to an Int64 will also work but if these strings become bigger or start to contain non-numerics, then you will have a problem.

string Key = "123456789012345";
string FormattedKey = Key.PadLeft(16, '0').Insert(12, "-").Insert(8, "-").Insert(4, "-");

That should be an alternative to formatting. It makes the key exactly 16 characters, then inserts three dashes from right to left. (Easier to keep track of indices.)

There are probably plenty of other alternatives but this one works just fine.



来源:https://stackoverflow.com/questions/1491699/string-format-does-not-works-for-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!