Lesson 4.5 · Write it
Repeat a character
A functionPython or Java6 tests, 3 of them hidden
On a phone? Put the lines in order instead
Write a function that returns a string made by repeating a character a given number of times.
chis a single character (a string of length 1).countis a whole number, always 1 or more.- Return a string of exactly
countcopies ofch. - Do not use string repetition (
*on a string in Python, or.repeatin Java).
Only the string your function returns is checked.
def repeat_char(ch: str, count: int) -> str
You cannot use these in this question:
- .__mul__()
- .__rmul__()
This question is about using a loop, so string repetition shortcuts are not allowed.
Examples
Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.
- repeat_char("*", 5) should return "*****": five stars (rule 3)
- repeat_char("a", 1) should return "a": one copy (rule 3)
- repeat_char("#", 3) should return "###": three hashes (rule 3)
public static String repeatChar(String ch, int count)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
You cannot use these in this question:
- .repeat()
This question is about using a loop, so string repetition shortcuts are not allowed.
Examples
Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.
- repeatChar("*", 5) should return "*****": five stars (rule 3)
- repeatChar("a", 1) should return "a": one copy (rule 3)
- repeatChar("#", 3) should return "###": three hashes (rule 3)