WAP to Reverse String Without Affecting Digits Position: In this program InterviewPrograms48, we are reversing the non-numeric substrings within a given string while leaving the numeric substrings unchanged.
Reverse String Without Affecting Digits Position
package com.softwaretestingo.interviewprograms; public class InterviewPrograms48 { /* * Input string : test986java656hello * Output : tset986avaj656olleh */ public static void main(String[] args) { String str="test986java656hello"; disp(str); } public static void disp(String str) { String[] strarr=str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); for (int i=0;i<strarr.length;i++) { if(! Character.isDigit(strarr[i].charAt(0))) { strarr[i]=rev(strarr[i]); } } String s2=String.join("", strarr); System.out.println(s2); } public static String rev(String str) { String rev=""; for(int i=str.length()-1;i>=0;i--) { rev=rev+str.charAt(i); } return rev; } }
Output
tset986avaj656olleh
Here’s a step-by-step explanation of the program:
- public static void main(String[] args): This is the entry point of the program. It starts by defining the input string “test986java656hello”.
- disp(str): The program calls the disp method and passes the input string as an argument.
- String[] strarr = str.split(“(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)”);: The input string is split into an array of substrings using regular expressions. The regular expression (?<=\\D)(?=\\d)|(?<=\\d)(?=\\D) matches the boundary between a non-digit and a digit, or the boundary between a digit and a non-digit. This splits the string into segments of continuous non-digits and digits.
- for (int i = 0; i < strarr.length; i++): The program iterates through each segment in the strarr array.
- if (!Character.isDigit(strarr[i].charAt(0))): If the first character of the segment is a non-digit, the program enters the if condition.
- strarr[i] = rev(strarr[i]);: The program calls the rev method and passes the segment as an argument. The rev method reverses the characters in the segment.
- String s2 = String.join(“”, strarr);: The program joins the modified segments back into a single string, using an empty string as the delimiter.
- System.out.println(s2);: The program prints the resulting string, which is the input string with non-digit segments reversed.
By the end of the program, the output is obtained as “tset986avaj656olleh”, where the non-digit segments in the input string are reversed while the digit segments remain unchanged.
Leave a Reply