Java > Warmup-2 > frontTimes (CodingBat Solution)

Problem:

Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;

frontTimes("Chocolate", 2) → "ChoCho"
frontTimes("Chocolate", 3) → "ChoChoCho"
frontTimes("Abc", 3) → "AbcAbcAbc"


Solution:

public String frontTimes(String str, int n) {
  int len = str.length();
  String temp = "";
  
  if (len < 4) {
    for (int i = 0; i < n; i++) {
      temp += str;
    }
  } else {
      for (int j = 0; j < n; j++) {
        temp += str.substring(0,3);
      }
  }
  
  return temp;
}

6 comments:

  1. private final String frontTimes(String word, int n) {
    if(n == 0){
    return "";
    }
    final String front = (word.length() <= 3)? word: word.substring(0, 3);
    final String repeat = (n <= 1)? front: front + frontTimes(front, n - 1);
    return repeat;
    }

    ReplyDelete
  2. int len =3;
    if(len> str.length()){
    len=str.length();
    }
    String result = "";
    for (int i=0; i<n; i++) {
    result= result + str.substring(0, len);
    }
    return result;

    ReplyDelete
  3. public String frontTimes(String str, int n) {
    if (n == 0) return "";
    if (str.length()<4) return str + frontTimes(str, n-1);
    return frontTimes(str.substring(0, 3), n);
    }

    ReplyDelete
  4. Another way

    public String frontTimes(String str, int n) {
    int substring = 3;

    if (substring > str.length()) {
    substring = str.length();
    }

    return String.join("", Collections.nCopies(n, str.substring(0, substring)));
    }

    ReplyDelete
  5. two ways:

    1)
    function frontTimes(str, n){
    const stringSplit = str.split("");
    let arr = [];
    for(let i = 0; i <= 2; i++){
    arr.push(stringSplit[i])
    }
    return arr.join("").repeat(n)
    }

    2)(and the simpler one)
    function frontTimes(str, n){
    return str.substring(0,3).repeat(n)
    }

    ReplyDelete