|
| 1 | +import java.util.Scanner; |
| 2 | +/* |
| 3 | + Input: This is my country |
| 4 | + Output: sihT is ym country |
| 5 | +*/ |
| 6 | +public class StringR { |
| 7 | + |
| 8 | + public static String[] split(String s) { |
| 9 | + int c = 0; |
| 10 | + for (int i = 0; i < s.length(); i++) { |
| 11 | + if (s.charAt(i) == ' ') { |
| 12 | + c += 1; |
| 13 | + } |
| 14 | + } |
| 15 | + String[] st = new String[c + 1]; |
| 16 | + String t = ""; |
| 17 | + int j = 0; |
| 18 | + for (int i = 0; i < s.length(); i++) { |
| 19 | + if (s.charAt(i) != ' ') { |
| 20 | + t += s.charAt(i); |
| 21 | + } else { |
| 22 | + st[j++] = t; |
| 23 | + t = ""; |
| 24 | + } |
| 25 | + } |
| 26 | + st[j] = t; |
| 27 | + return st; |
| 28 | + } |
| 29 | + |
| 30 | + public static String reverse(String str) { |
| 31 | + StringBuilder rev = new StringBuilder(""); |
| 32 | + if(str==null)return null; |
| 33 | + for(int i=str.length()-1;i>=0;i--) { |
| 34 | + rev.append(str.charAt(i)); |
| 35 | + } |
| 36 | + return rev.toString(); |
| 37 | + } |
| 38 | + |
| 39 | + public static void main(String[] args) { |
| 40 | + Scanner sc = new Scanner(System.in); |
| 41 | + System.out.println("Enter the String: "); |
| 42 | + String s = sc.nextLine(); |
| 43 | + sc.close(); |
| 44 | + String temp=""; |
| 45 | + String[] words=split(s); |
| 46 | + for(int i=0;i<words.length;i++) { |
| 47 | + if(i%2 == 0) |
| 48 | + temp+=reverse(words[i])+" "; |
| 49 | + else |
| 50 | + temp+=words[i]+" "; |
| 51 | + } |
| 52 | + System.out.println(temp); |
| 53 | + } |
| 54 | +} |
0 commit comments