Reverse Words Without Changing Order & Digits Position: This Java program takes an input string and reverses the characters within each word while preserving the order of numbers. The program uses nested loops to achieve this.
Reverse Words Without Changing Digits Position
package com.softwaretestingo.interviewprograms; public class InterviewPrograms28 { /* * Input String // My n@me is 12Rahul * Output String // yM em@n si 12luhaR * Only charcters should be Character, special characters and numbers should be displayed as it is. */ public static void main(String[] args) { String str = "My n@me is 12Rahul"; String result=""; String[] py = str.split(" "); int counter=0; for(int i=0;i<py.length;i++) { String tem = py[i]; for(int gg = tem.length()-1; gg>=0; gg--) { if(!Character.isDigit(tem.charAt(counter))) { result = result + tem.charAt(gg+counter); } else { result = result + tem.charAt(counter); counter++; } } result = result+ " "; counter=0; } System.out.println(result); } }
Output
yM em@n si 12luhaR
Alternative Way 1:
This Java program takes an input string and reverses the characters within each word while preserving the order of special characters and numbers. It utilizes Java 8 Stream API to achieve this.
package com.softwaretestingo.interviewprograms; import java.util.stream.Collectors; import java.util.stream.Stream; public class InterviewPrograms28_1 { /* * Input String // My n@me is 12Rahul * Output String // yM em@n si 12luhaR * Only charcters should be Character, special characters and numbers should be displayed as it is. */ public static void main(String[] args) { String str = "My n@me is 12Rahul"; String resultString = Stream.of(str.split(" ")).map(String::toCharArray).map(InterviewPrograms28_1::reverse) .collect(Collectors.joining(" ")); System.out.println(resultString); } public static String reverse ( char str [ ] ) { int left = 0 , right = str.length - 1 ; while ( left< right ) { // Ignore numbers characters if ( Character.isDigit ( str [left])) left ++ ; else if ( Character.isDigit ( str [right])) right-- ; else { char tmp = str [ left ] ; str [ left ] = str [ right ] ; str [ right ] = tmp ; left ++ ; right-- ; } } return new String ( str ) ; } }
Output
yM em@n si 12luhaR