String string 0 common methods of operation

Source: Internet
Author: User

String pre-complement 0

String string 0 or space in Java

Method One: Write your own method

/*

* Number of low digits left 0
*
* @param str
* @param strlength
*/
public static string Addzerofornum (string str, int strlength) {
int strLen = Str.length ();
if (StrLen < strlength) {
while (StrLen < strlength) {
StringBuffer sb = new StringBuffer ();
Sb.append ("0"). Append (str);//left complement 0
Sb.append (str). Append ("0");//Right complement 0
str = sb.tostring ();
StrLen = Str.length ();
}
}

return str;
}

Can fill "0" can also fill ""

Method 2: You need to determine how much to fill 0.

public class P {
public static void Main (string[] args) {
String pattern= "000";
Java.text.DecimalFormat df = new Java.text.DecimalFormat (pattern);
int i = 10,j=6;
System.out.println ("i=" +df.format (i) + "\nj=" +df.format (j));
}
}
---------------------Output-----------------------
i=010
j=006

Method 3: Using regular efficiency is very low, it is recommended to find other ways

/**
* Java Digital to string in front of auto-complement 0 implementation.
*
* @author Lao Zi Research Laboratory (laozizhu.com)
*
*/
. public class Teststringformat {
public static void Main (string[] args) {
int younumber = 1;
0 on behalf of the preceding supplement 0
4 for length 4
D for parameter is positive type
String str = String.Format ("%04d", Younumber);
System.out.println (str); 0001
}

----------
String a = "1a95e2c2a6";
String pattern= "0000000000000000";
System.out.println (pattern.substring (0, Pattern.length ()-a.length ()) +a);

String string 0 common methods of operation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.