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

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact