Java: Repeat (Understanding the code) -
could please explain how return line works? thank
public class javaapplication1 { /** * repeat string <b>str</b> <b>times</b> time. * @param str string repeat * @param times repeat str times time * @return generated string */ public static string repeat(string str, int times) { return new string(new char[times]).replace("\0", str); } public static void main(string[] args) { system.out.println(repeat("*", 5)); } }
it easier follow if broken down step step
// str = "*" , times = 5 public static string repeat(string str, int times) { //we crete new empty array have values {'\0','\0','\0','\0','\0'} char[] chararray = new char[times](); string newstr = new string(chararray); // newstr.equals("\0\0\0\0\0") newstr = newstr.replace('\0', str); //we replace '\0' "*" return newstr; //newstr.equals("*****") }
Comments
Post a Comment