Java > Warmup-2 > stringTimes (CodingBat Solution)

Problem:

Given a string and a non-negative int n, return a larger string that is n copies of the original string.

stringTimes("Hi", 2) → "HiHi"
stringTimes("Hi", 3) → "HiHiHi"
stringTimes("Hi", 1) → "Hi"


Solution:

public String stringTimes(String str, int n) {
  String temp = "";
  for (int i = 0; i < n; i++)
    temp += str;
  return temp;
}

6 comments:

  1. public String stringTimes(String word, int n) {
    if(n == 0){
    return "";
    }
    if(n > 1){
    return word + stringTimes(word, n - 1);
    }
    return word;
    }

    ReplyDelete
    Replies
    1. I think it is easier to do it without using recursion.

      Delete
  2. public String stringTimes(String str, int n) {
    String count="";
    for(int i=0; i=str.length()||n<=str.length())
    count+=str;
    }
    return count;
    }

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Another way

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

    ReplyDelete