Ask Question
1 March, 13:00

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.

+3
Answers (1)
  1. 1 March, 14:29
    0
    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
    ns + = newString;

    }

    return ns;

    }

    }

    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
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “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 ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers