Replace Last Two Special Character With Dots: This Java program aims to remove the last alphanumeric character from a given input string and replace it with dots.
Replace Last Two Special Character With Dots
package com.softwaretestingo.interviewprograms; public class InterviewPrograms40 { /* * Input string : Aut@oma#tion@# * Output: Aut@oma#tion.. * Input maybe any string, but only the last alphanumeric character should be removed */ public static void main(String[] args) { String s = "Aut@oma#tion@#"; String [ ] newstring = s.split(""); int count = 0 ; String last = ""; for ( int i = s.length()-1; i>=0;i--) { if (!newstring[i].matches("[a-zA-Z]")) { count++; last=last+"."; } else { break; } } System.out.print(s.substring(0, s.length()-count)+last); } }
Output
Aut@oma#tion..
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize the input string and split it into an array of characters:
- The string s is initialized with the value “Aut@oma#tion@#”.
- The split(“”) method is used to convert the input string into an array of characters named newstring.
- Find the last non-alphanumeric character:
- A variable count is initialized to zero to keep track of the number of non-alphanumeric characters at the end of the string.
- A variable last is initialized as an empty string to store the dots that will replace the removed characters.
- The program iterates through the characters in reverse order (from the end of the string to the beginning).
- If a character is not a letter (uppercase or lowercase) using the regex [a-zA-Z], it means it is non-alphanumeric.
- If the character is non-alphanumeric, the count is incremented, and a dot is appended to the last string.
- If a letter is encountered, the loop breaks since we have reached the last alphanumeric character.
- Build the output string:
- The program constructs the output string by removing the last count characters from the original string s and appending the last string (dots) at the end.
- Print the output:
- The program prints the final s string, which has the last alphanumeric character replaced with dots.
For the given input “Aut@oma#tion@#”, the program removes the last alphanumeric character “n” and replaces it with dots, resulting in “Aut@oma#tion..”.
Leave a Reply