我们可以使用String.format()填充所需长度的字符吗? [英] Can we use String.format() to pad/prefix with a character with desired length?

查看:382
本文介绍了我们可以使用String.format()填充所需长度的字符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用 java.lang.String.format(String str,String str1)来添加特定字符的前缀。



我可以这样做:

  int sendID = 202022; 
String usiSuffix = String.format(%032d,sendID);

它使长度为32的 String leftpadded用0s: 00000000000000000000000000202022



当sendID是一个字符串时如何达到同样的效果 like:

  String sendID =AABB; 

我想得到如下输出: 0000000000000000000000000000AABB

解决方案

您可以使用这种方法来获得您的输出:

  String sendID =AABB; 
String output = String.format(%0+(32-sendID.length())+d%s,0,sendID);



演示: http://ideone.com/UNVjqS


Can java.lang.String.format(String str, String str1) be used for adding prefix of a particular character.

I could do this for a number like:

int sendID = 202022;
String usiSuffix = String.format("%032d", sendID);

It makes a String of length 32 and leftpadded with 0s : 00000000000000000000000000202022

How to achieve the same thing when sendID is a String like:

String sendID = "AABB";

And I want an output like: 0000000000000000000000000000AABB

解决方案

You can use this hackish way to get your output:

String sendID = "AABB";
String output = String.format("%0"+(32-sendID.length())+"d%s", 0, sendID);

Demo: http://ideone.com/UNVjqS

这篇关于我们可以使用String.format()填充所需长度的字符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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