87.3k views
0 votes
Write a function in Java that implements the following logic: Given a string and an int n, return a string made of n repetitions of the last n characters of the string. You may assume that n is between 0 and the length of the string, inclusive.

User JBland
by
4.6k points

1 Answer

5 votes

Answer:

public class RepeatedString

{

public static void main(String[] args) {

System.out.println(repeatString("apple", 3));

}

public static String repeatString(String str, int n) {

String newString = str.substring(str.length()-n);

System.out.println(newString);

String ns = "";

for(int i=0; i<n; i++) {

ns += newString;

}

return ns;

}

}

Step-by-step explanation:

- Create a function called repeatString that takes two parameter

- Get the last n characters of the string using substring function, and assign it to the newString variable

- Initialize an empty string to hold the repeated strings

- Initialize a for loop that iterates n times

- Inside the loop, add the repeated strings to the ns

- When the loop is done, return ns

- Inside the main, call the function

User Jeremy Voisey
by
4.3k points