Printing reverse of any String without using any predefined function?

后端 未结 30 1310
生来不讨喜
生来不讨喜 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:09

    This is the simplest solution:

    System.out.print("egaugnal detatneiro tcejbo si avaj");
    
    0 讨论(0)
  • 2020-11-30 03:10

    Here you go:

    public static void main (String[] args) {
        System.out.println(reverserString("Akshay"));
    }
    
    private static String reverserString(String src) {
        char[] sArr = src.toCharArray();
        char[] dArr = new char[sArr.length];
        for(int i=sArr.length; i>0; i--) {
            dArr[sArr.length-i] = sArr[i-1];
        }
    
        return new String(dArr);
    }
    

    0 讨论(0)
  • 2020-11-30 03:11

    First of all: Why reinvent the wheel?

    That being said: Loop from the length of the string to 0 and concatenate into another string.

    0 讨论(0)
  • 2020-11-30 03:11
    public class MyStack {
       private int maxSize;
       private char[] stackArray;
       private int top;
       public MyStack(int s) {
          maxSize = s;
          stackArray = new char[maxSize];
          top = -1;
       }
       public void push(char j) {
          stackArray[++top] = j;
       }
       public char pop() {
          return stackArray[top--];
       }
       public char peek() {
          return stackArray[top];
       }
       public boolean isEmpty() {
          return (top == -1);
       }
       public boolean isFull() {
          return (top == maxSize - 1);
       }
       public static void main(String[] args) {
          MyStack theStack = new MyStack(10);
          String s="abcd";
          for(int i=0;i<s.length();i++)
          theStack.push(s.charAt(i));
          for(int i=0;i<s.length();i++)
          System.out.println(theStack.pop());
    
        }
    
    0 讨论(0)
  • 2020-11-30 03:12

    What is suprising is that most of the answers are wrong! When Unicode is used. Seems like no one understands that java uses UTF-16 under the hood for Text encoding.

    Here is my simple answer.

    static String reverseMe(String s) {
       StringBuilder sb = new StringBuilder();
    
       int count = s.codePointCount(0,s.length());
       for(int i = count - 1; i >= 0; --i)
         sb.append(Character.toChars(s.codePointAt(i)));
    
       return sb.toString();
     }
    
    0 讨论(0)
  • 2020-11-30 03:15

    How about a simple traverse from the end of the string to the beg:

    void printRev(String str) {
     for(int i=str.length()-1;i>=0;i--)
      System.out.print(str.charAt(i));
    }
    
    0 讨论(0)
提交回复
热议问题