Skip to content

L1-032 Left-pad

根据新浪微博上的消息,有一位开发者不满 NPM(Node Package Manager)的做法,收回了自己的开源代码,其中包括一个叫 left-pad 的模块,就是这个模块把 javascript 里面的 React/Babel 干瘫痪了。这是个什么样的模块?就是在字符串前填充一些东西到一定的长度。例如用*去填充字符串GPLT,使之长度为 10,调用 left-pad 的结果就应该是******GPLT。Node 社区曾经对 left-pad 紧急发布了一个替代,被严重吐槽。下面就请你来实现一下这个模块。

输入格式:

输入在第一行给出一个正整数N(≤104)和一个字符,分别是填充结果字符串的长度和用于填充的字符,中间以 1 个空格分开。第二行给出原始的非空字符串,以回车结束。

输出格式:

在一行中输出结果字符串。

输入样例 1:

tex
15 _
I love GPLT
15 _
I love GPLT

输出样例 1:

tex
____I love GPLT
____I love GPLT

输入样例 2:

4 *
this is a sample for cut
4 *
this is a sample for cut

输出样例 2:

cut
cut

Solution:

java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static String leftPad(int n, String shape, String s) {
        int length = s.length();
        if (length < n) {
            int count = n - length;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count; i++) {
                sb.append(shape);
            }
            return sb.append(s).toString();
        } else {
            return s.substring(length - n);
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String[] input = in.readLine().split(" ");
        int n = Integer.parseInt(input[0]);
        String shape = input[1];
        String s = in.readLine();
        System.out.println(leftPad(n, shape, s));
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static String leftPad(int n, String shape, String s) {
        int length = s.length();
        if (length < n) {
            int count = n - length;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count; i++) {
                sb.append(shape);
            }
            return sb.append(s).toString();
        } else {
            return s.substring(length - n);
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String[] input = in.readLine().split(" ");
        int n = Integer.parseInt(input[0]);
        String shape = input[1];
        String s = in.readLine();
        System.out.println(leftPad(n, shape, s));
    }
}

Released under the MIT License.