Printing reverse of any String without using any predefined function?

后端 未结 30 1316
生来不讨喜
生来不讨喜 2020-11-30 03:08

How to print the reverse of the String java is object orientated language without using any predefined function like reverse()?

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 03:22

    import java.util.Scanner;
    public class StringReverse {
        public static void main(String[] args) {
            //Read user Data From Console
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter Your String:");
            //Take an String so that it can Store the string data 
            String s1 = sc.nextLine();
            //split the string and keep in an array
            String[] s2 = s1.split(" ");
            String s3 = " ";
            //reverse  the string and placed in an String s3
            for (int i = 0; i < s2.length; i++) {
                for (int j= s2[i].length()-1;j>=0;j--) {
                    s3 += s2[i].charAt(j);
                }//for
                s3 += " ";
            }//for
    
            System.out.println("After Reverse: "+s3);
    
        }//main
    }//StringReverse
    

提交回复
热议问题