字符串功能-填充字符串

时间:2018-10-16 21:23:35

标签: javascript string function

leftPad函数通过将字符串填充到左侧使字符串具有一定长度。我们如何使leftPad函数如下工作?

// If the input is empty, return an empty string
leftPad('') // ''

// When given just a string, it returns that string
leftPad('abc') // 'abc'

// When given a string and a number, it will pad the string with spaces
// until the string length matches that number. Notice that the code
// below does NOT add four spaces -- rather, it pads the string until
// the length is four
leftPad('abc', 4) // ' abc'

// If the padding given is less than the length of the initial string,
// it just returns the string
leftPad('abc', 2) // 'abc'

// If given a third argument that is a single character, it will pad
// the string with that character
leftPad('abc', 6, 'z') // 'zzzabc'

这是问题第一部分的当前代码-如果输入为空,则返回一个空字符串:

function leftPad (string, padding, character) {
    let result = ""
    if (string.length === 0) {
        return result
    }

    if (string){

    }
}

2 个答案:

答案 0 :(得分:1)

我不会回答整个问题,因为这似乎是一个家庭作业问题。但是您可能可以充分利用内置的字符串repeat函数根据paddedString参数在左侧构建padding

function leftPad(string, padding, character) {
  let result = "", padCharacter = ' ';
  if (string.length === 0) {
    return result;
  }
  
  let paddedString = padCharacter.repeat(padding);
  console.log('Left padding will be "' + paddedString + '"');
  // return something
}

leftPad('hello', 5);
leftPad('world', 10);

答案 1 :(得分:0)

这是一个简单的解决方案,用于带或不带填充字符的左填充或右填充(默认为空白)。

示例:
字符串MyNewString = rightPad(MyOldString,12); 要么 字符串MyNewString = leftPad(MyOldString,8,“ 0”);

public static String leftPad(String string, int length) {
    return leftPad(string, length, " ");
}

public static String leftPad(String string, int length, String pad) {
    int L = string.length();
    if (L < length)
        return pad.repeat(length - string.length()) + string;
    else
        return string;
}

public static String rightPad(String string, int length) {
    return rightPad(string, length, " ");
}

public static String rightPad(String string, int length, String pad) {
    int L = string.length();
    if (L < length)
        return string + pad.repeat(length - string.length());
    else
        return string;
}