WAP to Replace a Character Sequence With Increase Order: The given Java program manipulates a given input string “HELLO WORLD” to replace each occurrence of the letter ‘L’ with a sequence of ‘x’ characters. The output will be “HExxxO WORxxxD,” where the number of ‘x’ characters increases for each occurrence of ‘L.’
Replace a Character Sequence With Increase Order
package com.softwaretestingo.interviewprograms; public class InterviewPrograms44 { /* * input: "HELLO WORLD" * Output: "HExxxO WORxxxD" */ public static void main(String[] args) { String s="HELLO WORLD"; String z=""; int count=1; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='L') { for(int j=0;j<count;j++) { z=z+'x'; } count++; } else { z=z+s.charAt(i); } } System.out.println(z); } }
Output
HExxxO WORxxxD
Here’s a step-by-step explanation of the program:
- Define the main method:
- The program starts executing from the main method.
- Initialize the input string:
- The input string s is initialized with the value “HELLO WORLD.”
- Initialize variables:
- A new string z is initialized to store the modified output.
- An integer variable count is initialized to keep track of the number of ‘x’ characters to be added for each ‘L’ occurrence. It is initially set to 1.
- Iterate through the input string:
- A loop runs from index 0 to the length of the string – 1.
- Check for ‘L’ occurrences:
- In each iteration, it checks if the character at the current index is ‘L.’
- If ‘L’ is found, it enters a nested loop.
- Add ‘x’ characters:
- The nested loop runs count times, and in each iteration, it appends ‘x’ to the string z.
- This will add ‘x’ characters based on the current value of count for each occurrence of ‘L.’
- Increment count:
- After the nested loop, count is incremented to increase the number of ‘x’ characters for the next ‘L’ occurrence.
- Add other characters:
- If the current character is not ‘L,’ it directly appends the character to the string z.
- Print the modified string:
- After the loop, the modified string z is printed as the output.
The program replaces each occurrence of ‘L’ with an increasing number of ‘x’ characters based on the variable count and outputs the final modified string “HExxxO WORxxxD.”
Leave a Reply