将前导零添加到字符串 [英] Add leading zeroes to a string

查看:59
本文介绍了将前导零添加到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字符串中添加一些前导零,总长度必须为8个字符.例如:

I want to add some leading zeroes to a string, the total length must be eight characters. For example:

123应该是00000123
1243应该是00001234
123456应该是00123456
12345678应该是12345678

123 should be 00000123
1243 should be 00001234
123456 should be 00123456
12345678 should be 12345678

最简单的方法是什么?

推荐答案

俗气的小把戏

String str = "123";
String formatted = ("00000000" + str).substring(str.length())

如果您改用数字开头:

Int number = 123;
String formatted = String.format("%08d", number);

这篇关于将前导零添加到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆