Printing reverse of any String without using any predefined function?

后端 未结 30 1314
生来不讨喜
生来不讨喜 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:29
    import java.util.*;
    public class Restring {
    
    public static void main(String[] args) {
      String input,output;
      Scanner kbd=new Scanner(System.in);
      System.out.println("Please Enter a String");
      input=kbd.nextLine();
      int n=input.length();
    
      char tmp[]=new char[n];
      char nxt[]=new char[n];
    
      tmp=input.toCharArray();
      int m=0;
      for(int i=n-1;i>=0;i--)
      {
          nxt[m]=tmp[i];
          m++;
      }
    
      System.out.print("Reversed String is   ");
      for(int i=0;i<n;i++)
      {
          System.out.print(nxt[i]);
      }
    
    }
    
    0 讨论(0)
  • 2020-11-30 03:30
    String reverse(String s) {
      int legnth = s.length();
      char[] arrayCh = s.toCharArray();
      for(int i=0; i< length/2; i++) {
          char ch = s.charAt(i);
          arrayCh[i] = arrayCh[legnth-1-i];
          arrayCh[legnth-1-i] = ch;
      } 
     return new String(arrayCh);
    }
    
    0 讨论(0)
  • 2020-11-30 03:32

    It can be done this way also

    char c[]=str.toCharArray();
      int i=c.lenght-1;
    public void printReverseString(char[] c, int i){
           if(i==-1) return;
           System.out.println(c[i]);
           printReverseString(c,--i);
       }   
    
    0 讨论(0)
  • 2020-11-30 03:33
    public class StringReverse {
    
        public static void main(String[] args) {
            String s= (args[0]);
            for (int i =s.length()-1; i >= 0; i--) {            
                   System.out.print(s.charAt(i));    
            }
        } 
    }
    

    Prints the reversed string of the input.

    0 讨论(0)
  • 2020-11-30 03:34
    public class StringReverse {
        public static void main(String ar[]){
            System.out.println(reverseMe("SRINIVAS"));
        }
        static String reverseMe(String s){
            StringBuffer sb=new StringBuffer();
            for(int i=s.length()-1;i>=0;--i){
                sb.append(s.charAt(i));
            }
            return sb.toString();
        }
    }
    
    0 讨论(0)
  • 2020-11-30 03:35

    You can do it either recursively or iteratively (looping).

    Iteratively:

     static String reverseMe(String s) {
       StringBuilder sb = new StringBuilder();
       for(int i = s.length() - 1; i >= 0; --i)
         sb.append(s.charAt(i));
       return sb.toString();
     }
    

    Recursively:

     static String reverseMe(String s) {
       if(s.length() == 0)
         return "";
       return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
     }
    
    0 讨论(0)
提交回复
热议问题