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


84. Repeated Truncating Prefixes

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



For more Practice: Solve these Related Problems:

  • Write a Java program to build a new string by concatenating progressively decreasing substrings from the beginning of a given string.
  • Write a Java program to form a pattern by taking the first p characters, then p-1, and so on, until empty.
  • Write a Java program to generate a composite string consisting of the initial substring of length p, followed by successive reductions.
  • Write a Java program to create a new string by successively removing the last character of the substring from the original string.

Go to:


PREV : Alternate Chars from Two Strings.
NEXT : Chars Around Substring.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.