IT story

선행 0으로 Java 문자열을 형식화하는 방법은 무엇입니까?

hot-time 2020. 5. 29. 23:46
반응형

선행 0으로 Java 문자열을 형식화하는 방법은 무엇입니까?


예를 들어 문자열은 다음과 같습니다.

"Apple"

8 문자를 채우기 위해 0을 추가하고 싶습니다.

"000Apple"

어떻게해야합니까?


도서관의 도움없이해야 할 경우 :

("00000000" + "Apple").substring("Apple".length())

(문자열이 8자를 넘지 않는 한 작동합니다.)


public class LeadingZerosExample {
    public static void main(String[] args) {
       int number = 1500;

       // String format below will add leading zeros (the %0 syntax) 
       // to the number above. 
       // The length of the formatted string will be 7 characters.

       String formatted = String.format("%07d", number);

       System.out.println("Number with leading zeros: " + formatted);
    }
}

 StringUtils.leftPad(yourString, 8, '0');

이것은 commons-lang에서 온 것 입니다. javadoc 참조


이것이 그가 정말로 요구 한 것입니다.

String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple"); 

산출:

000Apple

다른 답변에 사용 된 String.format 메소드를 사용하여 0의 문자열을 생성 할 수 있습니다.

String.format("%0"+length+"d",0)

형식 문자열에서 선행 0의 수를 동적으로 조정하여 문제에 적용 할 수 있습니다.

public String leadingZeros(String s, int length) {
     if (s.length() >= length) return s;
     else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}

여전히 지저분한 솔루션이지만 정수 인수를 사용하여 결과 문자열의 총 길이를 지정할 수 있다는 장점이 있습니다.


구아바의 Strings유틸리티 클래스 사용하기 :

Strings.padStart("Apple", 8, '0');

이것을 사용할 수 있습니다 :

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")

나는 비슷한 상황에 있었고 이것을 사용했습니다. 그것은 간결하고 길이나 다른 라이브러리를 다룰 필요가 없습니다.

String str = String.format("%8s","Apple");
str = str.replace(' ','0');

간단하고 깔끔합니다. " Apple"공백을 0으로 바꾸면 문자열 형식이 반환 되므로 원하는 결과를 얻을 수 있습니다.


String input = "Apple";
StringBuffer buf = new StringBuffer(input);

while (buf.length() < 8) {
  buf.insert(0, '0');
}

String output = buf.toString();

Apache Commons StringUtils.leftPad를 사용하십시오 (또는 자신의 기능을 수행하는 코드를보십시오).


엣지 케이스를 관리해야 할 수도 있습니다. 이것은 일반적인 방법입니다.

public class Test {
    public static void main(String[] args){
        System.out.println(padCharacter("0",8,"hello"));
    }
    public static String padCharacter(String c, int num, String str){
        for(int i=0;i<=num-str.length()+1;i++){str = c+str;}
        return str;
    }
}

public class PaddingLeft {
    public static void main(String[] args) {
        String input = "Apple";
        String result = "00000000" + input;
        int length = result.length();
        result = result.substring(length - 8, length);
        System.out.println(result);
    }
}

public static void main(String[] args)
{
    String stringForTest = "Apple";
    int requiredLengthAfterPadding = 8;
    int inputStringLengh = stringForTest.length();
    int diff = requiredLengthAfterPadding - inputStringLengh;
    if (inputStringLengh < requiredLengthAfterPadding)
    {
        stringForTest = new String(new char[diff]).replace("\0", "0")+ stringForTest;
    }
    System.out.println(stringForTest);
}

public static String lpad(String str, int requiredLength, char padChar) {
    if (str.length() > requiredLength) {
        return str;
    } else {
        return new String(new char[requiredLength - str.length()]).replace('\0', padChar) + str;
    }
}

자바에서 :

String zeroes="00000000";
String apple="apple";

String result=zeroes.substring(apple.length(),zeroes.length())+apple;

스칼라에서 :

"Apple".foldLeft("00000000"){(ac,e)=>ac.tail+e}

Java 8에서 스트림을 사용하여 수행하는 방법을 탐색하고 줄일 수 있습니다 (Scala로 수행 한 것과 유사). 그것은 다른 모든 솔루션과 약간 다르며 특히 많이 좋아합니다.


이것은 빠르고 길이에 관계없이 작동합니다.

public static String prefixZeros(String value, int len) {
    char[] t = new char[len];
    int l = value.length();
    int k = len-l;
    for(int i=0;i<k;i++) { t[i]='0'; }
    value.getChars(0, l, t, k);
    return new String(t);
}

대부분의 문자열에서 8 문자가 정확할 때 Chris Lercher가 응답하는 것보다 빠를 수 있습니다.

int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);

내 경우에는 내 컴퓨터에서 1/8 더 빠릅니다.


Here is the simple API-less "readable script" version I use for pre-padding a string. (Simple, Readable, and Adjustable).

while(str.length() < desired_length)
  str = '0'+str;

Did anyone tried this pure Java solution (without SpringUtils):

//decimal to hex string 1=> 01, 10=>0A,..
String.format("%1$2s", Integer.toString(1,16) ).replace(" ","0");
//reply to original question, string with leading zeros. 
//first generates a 10 char long string with leading spaces, and then spaces are
//replaced by a zero string. 
String.format("%1$10s", "mystring" ).replace(" ","0");

Unfortunately this solution works only if you do not have blank spaces in a string.


It isn't pretty, but it works. If you have access apache commons i would suggest that use that

if (val.length() < 8) {
  for (int i = 0; i < val - 8; i++) {
    val = "0" + val;
  }
}

참고URL : https://stackoverflow.com/questions/4051887/how-to-format-a-java-string-with-leading-zero

반응형