왼쪽 채우기

1562 단어 lintcode레코드
leftpad 라이브러리를 실행합니다. leftpad가 무엇인지 모르면 예시를 볼 수 있습니다.
예제
leftpad("foo", 5)
>> "  foo"

leftpad("foobar", 6)
>> "foobar"

leftpad("1", 2, "0")
>> "01"

String 객체는 변경할 수 없습니다.System을 사용할 때마다String 클래스의 방법 중 하나는 메모리에 새 문자열 대상을 만들어야 하기 때문에 새 대상에 새로운 공간을 할당해야 한다.문자열에 대한 중복 수정이 필요한 경우 새 String 대상을 만드는 것과 관련된 시스템 비용이 매우 비쌀 수 있습니다.새 객체를 만들지 않고 문자열을 수정하려면 System을 사용할 수 있습니다.Text.StringBuilder 클래스.예를 들어 하나의 순환에 많은 문자열을 연결할 때 StringBuilder 클래스를 사용하면 성능[동적 대상]을 향상시킬 수 있다.
public class StringUtils {
   /**
     * @param originalStr the string we want to append to with spaces
     * @param size the target length of the string
     * @return a string
     */
    static public String leftPad(String originalStr, int size) {
       //Write your code here
        return leftPad(originalStr,size,' ');
    }
   /**
     * @param originalStr the string we want to append to
     * @param size the target length of the string
     * @param padChar the character to pad to the left side of the string
     * @return a string
     */
    static public String leftPad(String originalStr, int size, char padChar) {
       //Write your code here
        int len = originalStr.length();
        StringBuilder str = new StringBuilder();
        for(int i=0;i            str.append(padChar);
        return str.append(originalStr).toString();
    }
}

좋은 웹페이지 즐겨찾기