programing

왼쪽에 0이 있는 정수를 채우려면 어떻게 해야 하나요?

sourcetip 2022. 7. 19. 22:56
반응형

왼쪽에 0이 있는 정수를 채우려면 어떻게 해야 하나요?

패드를 어떻게 남기지?int로 변환할 때 0을 사용하여String자바어?

난 기본적으로 정수를 2배 이상 채우려고 해9999선행 0(예: 1 =)을 사용합니다.0001).

다음과 같이 사용:

String.format("%05d", yournumber);

길이 5의 제로 타임에 대응합니다.16진수 출력의 경우d와 함께x에서와 같이"%05x".

완전 포맷옵션은 의 일부로 설명하겠습니다.

예를 들어, 인쇄하고 싶다고 합시다.11~하듯이011

포메터를 사용할 수 있습니다."%03d".

여기에 이미지 설명 입력

이 포메터는 다음과 같이 사용할 수 있습니다.

int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);

또는 일부 Java 메서드는 다음 포메터를 직접 지원합니다.

System.out.printf("%03d", a);

어떤 이유로든 1.5 이전 Java를 사용하는 경우 Apache Commons Lang 메서드를 사용할 수 있습니다.

org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')

이 예제를 찾았습니다...테스트...

import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
    public static void main(String [] args)
    {
        int x=1;
        DecimalFormat df = new DecimalFormat("00");
        System.out.println(df.format(x));
    }
}

이것을 테스트하고,

String.format("%05d",number);

둘 다 효과가 있어, 내 생각엔 스트링인 것 같아.형식이 더 좋고 더 간결합니다.

이것을 사용해 보세요.

import java.text.DecimalFormat; 

DecimalFormat df = new DecimalFormat("0000");

String c = df.format(9);   // Output: 0009

String a = df.format(99);  // Output: 0099

String b = df.format(999); // Output: 0999

퍼포먼스가 중요한 경우, 퍼포먼스를 직접 실현하는 것으로,String.format기능:

/**
 * @param in The integer value
 * @param fill The number of digits to fill
 * @return The given value left padded with the given number of digits
 */
public static String lPadZero(int in, int fill){

    boolean negative = false;
    int value, len = 0;

    if(in >= 0){
        value = in;
    } else {
        negative = true;
        value = - in;
        in = - in;
        len ++;
    }

    if(value == 0){
        len = 1;
    } else{         
        for(; value != 0; len ++){
            value /= 10;
        }
    }

    StringBuilder sb = new StringBuilder();

    if(negative){
        sb.append('-');
    }

    for(int i = fill; i > len; i--){
        sb.append('0');
    }

    sb.append(in);

    return sb.toString();       
}

성능

public static void main(String[] args) {
    Random rdm;
    long start; 

    // Using own function
    rdm = new Random(0);
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        lPadZero(rdm.nextInt(20000) - 10000, 4);
    }
    System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");

    // Using String.format
    rdm = new Random(0);        
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        String.format("%04d", rdm.nextInt(20000) - 10000);
    }
    System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}

결과

자체 기능 : 1697ms

String.format: 38134ms

Google Guava를 사용할 수 있습니다.

메이븐:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

샘플 코드:

String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"

주의:

Guava매우 유용한 라이브러리입니다.또한 다음과 같은 많은 기능을 제공합니다.Collections,Caches,Functional idioms,Concurrency,Strings,Primitives,Ranges,IO,Hashing,EventBus,기타

참고 자료: Guava 설명

다음은 를 사용하지 않고 문자열을 포맷하는 방법입니다.DecimalFormat.

String.format("%02d", 9)

09

String.format("%03d", 19)

019

String.format("%04d", 119)

0119

위의 접근법 중 많은 것이 좋기는 하지만 때로는 플로트 형식뿐만 아니라 정수 형식도 지정해야 합니다.특히 왼쪽과 오른쪽의 특정 숫자 0을 패딩해야 할 때 이 기능을 사용할 수 있습니다.

import java.text.NumberFormat;  
public class NumberFormatMain {  

public static void main(String[] args) {  
    int intNumber = 25;  
    float floatNumber = 25.546f;  
    NumberFormat format=NumberFormat.getInstance();  
    format.setMaximumIntegerDigits(6);  
    format.setMaximumFractionDigits(6);  
    format.setMinimumFractionDigits(6);  
    format.setMinimumIntegerDigits(6);  

    System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));  
    System.out.println("Formatted Float   : "+format.format(floatNumber).replace(",",""));  
 }    
}  
int x = 1;
System.out.format("%05d",x);

포맷된 텍스트를 화면에 직접 인쇄하려면 를 누릅니다.

포맷터를 사용해야 합니다.다음 코드는 번호를 사용합니다.포맷

    int inputNo = 1;
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumIntegerDigits(4);
    nf.setMinimumIntegerDigits(4);
    nf.setGroupingUsed(false);

    System.out.println("Formatted Integer : " + nf.format(inputNo));

출력: 0001

다음과 같이 DecimalFormat 클래스를 사용합니다.

NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811)); 

출력: 0000811

다음과 같이 문자열에 선행 0을 추가할 수 있습니다.원하는 문자열의 최대 길이가 되는 문자열을 정의합니다.저 같은 경우에는 길이가 9자밖에 안 되는 끈이 필요해요.

String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);

출력: 000602939

정수와 문자열로 동작하는 코드를 확인합니다.

첫 번째 숫자가 2라고 가정하자.여기에 0을 더하면 마지막 문자열의 길이는 4가 됩니다.그러기 위해 다음 코드를 사용할 수 있습니다.

    int number=2;
    int requiredLengthAfterPadding=4;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);

이 간단한 확장 기능 사용

fun Int.padZero(): String {
    return if (this < 10) {
        "0$this"
    } else {
        this.toString()
    }
}

코틀린의 경우

fun Calendar.getFullDate(): String {
    val mYear = "${this.get(Calendar.YEAR)}-"
    val mMonth = if (this.get(Calendar.MONTH) + 1 < 10) {
        "0${this.get(Calendar.MONTH) + 1}-"
    } else {
        "${this.get(Calendar.MONTH)+ 1}-"
    }
    val mDate = if (this.get(Calendar.DAY_OF_MONTH)  < 10) {
        "0${this.get(Calendar.DAY_OF_MONTH)}"
    } else {
        "${this.get(Calendar.DAY_OF_MONTH)}"
    }
    return mYear + mMonth + mDate
}

그리고 그것을 로서

val date: String = calendar.getFullDate()

다음은 왼쪽에 0을 사용하여 정수를 채우는 다른 방법입니다.필요에 따라 제로 수를 늘릴 수 있습니다.마이너스 번호 또는 설정된0보다 크거나 같은 값의 경우와 같은 값을 반환하기 위한 체크가 추가되었습니다.필요에 따라 추가로 수정할 수 있습니다.

/**
 * 
 * @author Dinesh.Lomte
 *
 */
public class AddLeadingZerosToNum {
    
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        
        System.out.println(getLeadingZerosToNum(0));
        System.out.println(getLeadingZerosToNum(7));
        System.out.println(getLeadingZerosToNum(13));
        System.out.println(getLeadingZerosToNum(713));
        System.out.println(getLeadingZerosToNum(7013));
        System.out.println(getLeadingZerosToNum(9999));
    }
    /**
     * 
     * @param num
     * @return
     */
    private static String getLeadingZerosToNum(int num) {
        // Initializing the string of zeros with required size
        String zeros = new String("0000");
        // Validating if num value is less then zero or if the length of number 
        // is greater then zeros configured to return the num value as is
        if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
            return String.valueOf(num);
        }
        // Returning zeros in case if value is zero.
        if (num == 0) {
            return zeros;
        }
        return new StringBuilder(zeros.substring(0, zeros.length() - 
                String.valueOf(num).length())).append(
                        String.valueOf(num)).toString();
    }
}

입력

0

7

13

713

7013

9999

산출량

0000

0007

0013

7013

9999

패키지는 필요 없습니다.

String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;

이렇게 하면 문자열이 3자로 패딩되어 4자 또는 5자분의 부품을 쉽게 추가할 수 있습니다.어떤 식으로든 완벽한 해결책이 아니라는 것을 알지만(특히 큰 패딩을 원하는 경우) 마음에 듭니다.

언급URL : https://stackoverflow.com/questions/473282/how-can-i-pad-an-integer-with-zeros-on-the-left

반응형