Ask 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 last n characters of the string. You may assume that n is between 0 and the length of the string, inclusive.

+4
Answers (1)
  1. 9 November, 03:40
    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?
Find 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 the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers