|
| 1 | +package powerJavaLearning; |
| 2 | + |
| 3 | +public class ReverseEvenWordsInAStringUsingStringBuffer { |
| 4 | + |
| 5 | + /*Write a java program to do the following. |
| 6 | + * Input: "When the world realise its own mistakes, corona will dissolve automatically" |
| 7 | + * output: "When eht world esilaer its nwo mistakes, anoroc will evlossid automatically" |
| 8 | + * */ |
| 9 | + |
| 10 | + public static void main(String[] args) { |
| 11 | + String input = "When the world realise its own mistakes, corona will dissolve automatically"; |
| 12 | + String[] inputSplit= input.split(" "); |
| 13 | + |
| 14 | + |
| 15 | + //String Reversal Using append function |
| 16 | + System.out.println("Reversal using Append " ); |
| 17 | + StringBuffer tempString01 = new StringBuffer(); |
| 18 | + for (int i = 0; i < inputSplit.length; i++) { |
| 19 | + if ((i%2) != 0) { |
| 20 | + tempString01.append(new StringBuffer(inputSplit[i]).reverse()).append(" "); |
| 21 | + } else { |
| 22 | + tempString01.append(new StringBuffer(inputSplit[i])).append(" "); |
| 23 | + } |
| 24 | + } |
| 25 | + System.out.println(tempString01); |
| 26 | + |
| 27 | + |
| 28 | + //String Reversal Using reverse function |
| 29 | + System.out.println("Reversal using reverse " ); |
| 30 | + for (int i = 0; i < inputSplit.length; i++) { |
| 31 | + if ((i%2) != 0) { |
| 32 | + StringBuffer tempString02 = new StringBuffer(inputSplit[i]); |
| 33 | + inputSplit[i] = tempString02.reverse().toString(); |
| 34 | + } |
| 35 | + } |
| 36 | + for (int i = 0; i < inputSplit.length; i++) { |
| 37 | + System.out.print(inputSplit[i] + " "); |
| 38 | + } |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | +} |
0 commit comments