w3resource

Java: Make a new string made of p number of characters from the first of a given string and followed by p-1 number characters till the p is greater than zero

Java String: Exercise-84 with Solution

Write a Java program to make an original string made of p number of characters from the first character in a given string. This is followed by p-1 number of characters till p is greater than zero.

Sample Solution:

Java Code:

import java.util.*;

// Define a class named Main
public class Main {

  // Method to repeat the beginning characters of a string 'stng' 'n' times
  public String beginningRepetition(String stng, int n) {
    int l = stng.length(); // Get the length of the input string 'stng'
    String newstring = ""; // Initialize an empty string to store the new string
    
    // Loop 'n' times to repeat the beginning characters
    for (int i = n; n > 0; n--) {
      newstring += stng.substring(0, n); // Append the substring from index 0 to 'n' of 'stng' to 'newstring'
    }
    return newstring; // Return the new string
  }

  // Main method to execute the program
  public static void main(String[] args) {
    Main m = new Main(); // Create an instance of the Main class

    String str1 = "welcome"; // Input string
    int rep_no = 4; // Number of repetitions

    // Display the given string, the number of repetitions, and the new string after repetition
    System.out.println("The given string is: " + str1);
    System.out.println("Number of repetition characters and repetition: " + rep_no);
    System.out.println("The new string is: " + m.beginningRepetition(str1, rep_no));
  }
}

Sample Output:

The given string is: welcome
Number of repetition characters and repetition: 4
The new string is: welcwelwew

Flowchart:

Flowchart: Java String Exercises - Make a new string made of p number of characters from the first of a given string and followed by p-1 number characters till the p is greater than zero

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to make a new string from two given string in such a way that, each character of two string will come respectively.
Next: Write a Java program to make a new string with each character of just before and after of a non-empty substring whichever it appears in a non-empty given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/string/java-string-exercise-84.php