字符串格式不适用于字符串

发布于 2024-08-06 00:57:54 字数 177 浏览 4 评论 0原文

我有一个字符串类型的序列号。

像这样;

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

我需要看像这样,1234-5678-9123-4567;

这段代码不起作用?

你能帮助我吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红焚 2024-08-13 00:57:54

该语法需要一个 int,请尝试以下操作:

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

编辑:如果您想在字符串上使用此语法,请尝试以下操作:

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

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"))
压抑⊿情绪 2024-08-13 00:57:54

对于####-####-####-####,您将需要一个号码。但你给它喂了一根绳子。

在字符串左侧填充额外的零会更实用,这样它就变成了 16 个字符。然后在字符串内的三个位置插入破折号。将其转换为 Int64 也可以,但如果这些字符串变得更大或开始包含非数字,那么您就会遇到问题。

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

这应该是格式化的替代方法。它使密钥恰好为 16 个字符,然后从右到左插入三个破折号。 (更容易跟踪索引。)

可能还有很多其他选择,但这个效果很好。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文