Reverse a string in Java

前端 未结 30 2631
礼貌的吻别
礼貌的吻别 2020-11-21 13:12

I have \"Hello World\" kept in a String variable named hi.

I need to print it, but reversed.

How can I do this? I understand there

30条回答
  •  失恋的感觉
    2020-11-21 14:04

    One natural way to reverse a String is to use a StringTokenizer and a stack. Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.

    String s = "Hello My name is Sufiyan";
    

    Put it in the stack frontwards

    Stack myStack = new Stack<>();
    StringTokenizer st = new StringTokenizer(s);
    while (st.hasMoreTokens()) {
         myStack.push(st.nextToken());
    }
    

    Print the stack backwards

    System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
    while (!myStack.empty()) {
      System.out.print(myStack.pop());
      System.out.print(' ');
    }
    
    System.out.println('"');
    

提交回复
热议问题