Reverse a word with a function

edited November 2016 in How To...

Hello!

I want to make a program that includes a function. The function should reverse a word. For example if I type in Hello, it should end up with olleH. My question is how the code would look like for this program.

Thank you in advance, Lugi5000

Answers

  • String txt = "Ipsis Lorem";
    String rev = new String(reverse(txt.toCharArray()));
    
    println(txt);
    println(rev);
    
    exit();
    
  • Thank you for your answer!

  • String txt = "Ipsis Lorem";
    String rev = new StringBuilder(txt).reverse().toString();
    
    println(txt);
    println(rev);
    
    exit();
    
  • @Lugi5000 -- Notice that the solution by @GoToLoop treats the string as a list of characters (a character array). You can use reverse() to reverse any array.

  • @jeremydouglass But what if I reverse the word with a string and the command return?

  • I don't understand. Is that a question? What if...?

  • @jeremydouglass Yes this is a question. I am sorry, I am from Austria :)

  • edited November 2016 Answer ✓
    /**
     * Reverse String (v1.1)
     * GoToLoop (2016-Nov-16)
     *
     * forum.Processing.org/two/discussion/19072/
     * reverse-a-word-with-a-function#Item_8
     */
    
    String txt = "Ipsis Lorem", rev;
    
    void setup() {
      rev = reverseString(txt);
      println(txt);
      println(rev);
      exit();
    }
    
    static final String reverseString(final CharSequence str) {
      return new StringBuilder(str).reverse().toString();
    }
    
  • Oh, I see. "What if" is perfectly good English -- I just wasn't understanding "and the command return." You want to use a function, and then return its value with return, like in GoToLoop's example.

Sign In or Register to comment.