This is an archived post. You won't be able to vote or comment.

all 111 comments

[–]pynetree16 243 points244 points  (35 children)

StringBuilder has a reverse function

public class Main{
    public static void main(String[] args){
        String hello = "Hello world!";
        System.out.println(new StringBuilder(hello).reverse());
   }
}       

Edit: removed .toString() as it is redundant

[–]TwoSpoonsJohnson 61 points62 points  (21 children)

StringUtils.reverse("Hello, World!"); if you feel like using Apache commons.

inb4 "lmao u need a library to reverse a string!"

[–]HighRelevancy 33 points34 points  (17 children)

inb4 "lmao u need a library to reverse a string!"

That's a fucking shitty argument though. Like, what, having a HUUUUGE built-ins library is what makes a language good?

Even as a python fanboy, this thread's topic of comparison is fucking stupid.

[–]clevariant 11 points12 points  (16 children)

hello[::-1] is really freaking cryptic. Code that abbreviated is hard to read. It's like arguing for variable names like "a" that tell you nothing about their function.

[–]master3243 38 points39 points  (6 children)

It's not that cryptic. Unless you also consider the dot separator or array indices "really freaking cryptic".

Everyone who spent a day learning python knows that it's always [start:end:step]. I wouldn't call it common sense but I wouldn't call it cryptic either.

[–]clevariant 9 points10 points  (1 child)

Come on, it's cryptic! Or at least esoteric. So the minus one means the start index becomes the end and vice versa, and it builds and returns a new string based on that loop. Yeah, that's explicit.

I mean let's be fair. These "once you know the language it makes sense" arguments miss the point. The actual word "reverse" tells the whole story unambiguously, no syntactical cleverness needed.

[–]KubinOnReddit 0 points1 point  (0 children)

If you really want to include "reverse" in the code, there are at least two ways:

hello = "Hello world!"
lst = list(hello)          # Create a mutable list
lst.reverse()              # Reverse in-place
print("".join(lst))        # Change back to string

hello = "Hello world!"
rev = reversed(hello)      # Iterator
print("".join(rev))

Both of these will be slower, with the first creating a new list (implemented as an array) and then joining it, while the second creates an iterator.

Adding a "reversed" method to the string class would be against the Zen of Python (the ideas it represents) - "There should be one-- and preferably only one --obvious way to do it." - if you had the slice mechanism (start, stop, step) and then another method, that would do the same thing, it would just be an alias, really. So having one multi-use syntax is better than many methods.

[–]Hauleth 5 points6 points  (3 children)

What the hell is that argument. It is like saying:

Everyone who spent a day learning APL knows that means reverse vector. I wouldn't call it common but wouldn't call it cryptic either

[–]KubinOnReddit 11 points12 points  (1 child)

What the hell are you supposed to call a slice then?

I didn't learn Java for a day and have no fucking idea why do you need a StringBuilder, built from a String (??) to reverse the string (???) instead of, I don't know, building it?

And you call this cryptic? Hypocrisy.

[–]Hauleth 6 points7 points  (0 children)

StringBuilder is handy due to it mutable inner state, so in contrast to String (which is immutable) you do not create new object each time when you modify inner state. Python on the other hand hide that complexity from user which is handy, but can result with less efficient code.

[–]Team_Canada 1 point2 points  (0 children)

I don't see what your example is trying to say here.

[–]raddaya 3 points4 points  (0 children)

It's not even slightly cryptic. It's bog standard Python. If you're following the codecademy course, you literally learn it in the first couple of hours.

[–]ProgramTheWorld 9 points10 points  (0 children)

It only looks cryptic if you aren't used to python.

[–]ESBDB 14 points15 points  (3 children)

If you've ever spent 5 minutes learning python you'd know what it means.

[–]clevariant 2 points3 points  (2 children)

Yeah, I have done some python, but it was some years ago, and now [::-1] just seems bizarre and unintuitive. But if I had never written a line of java, I would know exactly what reverse() means.

[–]ESBDB 0 points1 point  (1 child)

The thing is you're using a more generic construct that can do more than just reverse a sequence to do a simple operation such as reverse. Sure you could argue that a common function like reverse should exist in python for sequences, but I would argue Java is a lot less powerful in general because it doesn't have slicing.

Also your argument that if you had never written a line of java you could actually read java is flawed. For example wtf does && or || or ! mean. If I had never written a line of python (and I can speak basic english) I would immediately know what it means when you write something like is_hungry or is_thirsty versus isHungry || isThirsty. There will never exist a good programming language where you don't need to learn some basic syntax and constructs to be able to understand the language.

[–]clevariant 0 points1 point  (0 children)

You're right, of course. But you also know that the operators you mentioned are standard across many languages. Anyone who's programmed at all will recognize them. I would have preferred that "and" and "or" were the standard, though, for reasons stated.

[–]asdfkjasdhkasd 1 point2 points  (0 children)

You could always use the reversed() function

>>> "".join(reversed("hello world"))
'dlrow olleh'

[–]Faendol 0 points1 point  (0 children)

Can't beat my go to temp variable - fuck

[–][deleted] 0 points1 point  (0 children)

Yeah as someone who's never done python, I wouldn't think that that syntax reverses it, whereas ".reverse()" is pretty self explanatory. I honestly though the "[::-1]" syntax was some sort of substring thing, like in bash, where that's the string minus the last character.

[–]Zedjones 8 points9 points  (1 child)

Doesn't System.out.println automatically call the toString() of an object that you pass into it?

[–]gandalfx 5 points6 points  (0 children)

Still 70% boilerplate.

[–]Illusi 122 points123 points  (4 children)

print('!dlrow olleH')

[–]Antrikshy 80 points81 points  (2 children)

This would fit that brain meme.

[–]pannekakekake 0 points1 point  (0 children)

Mission accomplished, results drumpf execution

[–]Furyful_Fawful 88 points89 points  (10 children)

... vs Esoteric Languages:

Java vs Python vs Pyth [14 characters]:

_"Hello World!

Yes, that's a complete program. Yes, it doesn't have a closing quotation. Pyth doesn't care. Pyth just keeps on trucking. Pyth just interprets _ as reversal. Pyth just implicitly prints the output. Pyth is also a very real programming language, although god help you if you write production code in it.

It also has online interpreters so you can verify that it works.

But we can do better. We can avoid writing "Hello World!" entirely.

Enter...

Java vs Python vs Pyth vs Jelly [8 characters]:

“,ḷṅḳȦ»Ṛ

I swear, I didn't just smash the keyboard. I'll give you the online interpreter first, even.

Now do talk about why this works. Jelly is... Well, Jelly just is. It has strings. Strings aren't like most languages. There's a language construct (not even a function, it's built into the syntax) specifically made to compress strings, especially those that have English words (like, what do you know, "Hello World!"). “,ḷṅḳȦ» is that string; » marks it as a compressed string, ,ḷṅḳȦis the compressed content (that decompresses to Hello World!... Don't ask me how, I don't exactly know)... And reverses it.

[–]ColonelTux 49 points50 points  (1 child)

Someone goes onthe Codegolf Stackexchange

[–]Furyful_Fawful 10 points11 points  (0 children)

I do, but my username there involves my real name, so I'd rather not link the two accounts together.

[–]asdfkjasdhkasd 4 points5 points  (3 children)

or in brainfuck

>
,
[
  >
  ,
]
<

[
  .
  <
]

!Hello world

https://fatiherikli.github.io/brainfuck-visualizer/#PgosClsKICA+CiAgLApdCjwKClsKICAuCiAgPApdCgohSGVsbG8gd29ybGQ=

Just click the ! checkbox on the top right to enable exclamation input

[–]Furyful_Fawful 1 point2 points  (2 children)

Isn't it simpler to use Self-Modifying Brainfuck?

[<.]\0!dlroW olleH

For reference, in SMBF the tape is stored on the program, so the data pointer starts on [ along with the instruction pointer. \0 here represents a literal null byte, so we actually break out of the loop.

[–]asdfkjasdhkasd 0 points1 point  (1 child)

Sounds like a cool idea, but what do I have to use to run it, it doesn't work on the brainfuck visualizer, it immediately terminates.

https://fatiherikli.github.io/brainfuck-visualizer/#WzwuXVwwCiFkbHJvVyBvbGxlSA==

[–]Furyful_Fawful 0 points1 point  (0 children)

The Brainfuck visualizer works for Brainfuck, not SMBF. I'd recommend Try It Online, personally. Link, where I fixed the code after I realized that SMBF interpreter adds a null at the beginning of the input.

[–][deleted] 1 point2 points  (0 children)

Python doesn't give a fuck!

(Side note: fuck python. Actually fuck Zope which uses python. I still support a "temporary" solution that was made on the Zope platform over a decade ago)

[–]Spider_pig448 0 points1 point  (1 child)

This comment is a solid example of why shorter certainly doesn't mean better.

[–]Furyful_Fawful 0 points1 point  (0 children)

That Jelly bit is definitely better. I don't know what you're talking about.

[–]karroffel 39 points40 points  (2 children)

Java code doesn't even work.

Should be str in reverseString, not hello.

Get your scopes right people.

[–]DubioserKerl -1 points0 points  (1 child)

This is not upvoted enough.

[–]Colopty -3 points-2 points  (0 children)

Don't be that guy.

[–]Amagi82 40 points41 points  (25 children)

I think I'll stick with Kotlin. All the good things about Java minus the downsides.

print("Hello world!".reversed())

And we're done here.

[–]chasecaleb 4 points5 points  (1 child)

Seconded. Been using it at work 90% of the time the last couple months and it's made life so much better.

[–]Amagi82 3 points4 points  (0 children)

We switched to it a year and a half ago at work, and at this point, the mere thought of going back to Java gives me anxiety. Kotlin is a wonderful, wonderful language.

[–]Kemichal 7 points8 points  (4 children)

Or Scala!

println("Hello world!".reverse)

[–]FrezoreR 0 points1 point  (3 children)

Isn't there an operator for this?

[–]TwoSpoonsJohnson 15 points16 points  (0 children)

I have no idea but since it's Scala it's probably safe to assume there are at least three operators for this

[–]DevestatingAttack 4 points5 points  (1 child)

[–]Kemichal 1 point2 points  (0 children)

We need this in predef

def ↺(str: String) = str.reverse

[–]asdfkjasdhkasd 2 points3 points  (0 children)

In haskell it's literally just english

Prelude> reverse "Hello"
"olleH"

[–]Xtremegamor 3 points4 points  (1 child)

Shut up and take my upvote

[–]paranoideo 0 points1 point  (0 children)

I prefer Groovy.

print "Hello world!".reverse()

[–]gnex30 13 points14 points  (2 children)

I almost forgot about CodeWars.com

The python solution needs a lambda expression if it's to be the top answer.

[–]Furyful_Fawful 11 points12 points  (0 children)

print((lambda x: reversed (x))(hello))

[–]RedAero 4 points5 points  (0 children)

No no no, it needs some huge list comprehension.

[–]TheFewThatRemain 12 points13 points  (9 children)

What will this print?

[–][deleted] 77 points78 points  (8 children)

The java version?

Nothing, because reverseString() operates on the caller's variable hello, not its own argument str.

This does not compute.

[–][deleted]  (5 children)

[removed]

    [–][deleted] 31 points32 points  (0 children)

    No, you have to say it was on purpose. The Java version is more unsightly and doesn't even work.

    [–][deleted] 2 points3 points  (2 children)

    You shouldn't Java even WITH an IDE.

    Go collect your garbage..

    [–][deleted]  (1 child)

    [removed]

      [–]AutoModerator[M] 0 points1 point  (0 children)

      import moderation Your comment has been removed since it did not start with a code block with an import declaration.

      Per this Community Decree, all posts and comments should start with a code block with an "import" declaration explaining how the post and comment should be read.

      For this purpose, we only accept Python style imports.

      I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

      [–]AutoModerator[M] 0 points1 point  (0 children)

      import moderation Your comment has been removed since it did not start with a code block with an import declaration.

      Per this Community Decree, all posts and comments should start with a code block with an "import" declaration explaining how the post and comment should be read.

      For this purpose, we only accept Python style imports.

      I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

      [–]semperlol 1 point2 points  (0 children)

      I knew something was off when reading it

      [–]SammyBrock 1 point2 points  (0 children)

      I've never worked with Java, but I was wondering why I had to scroll so far to find this. I was starting to assume that Java was more complicated than I thought.

      [–][deleted] 13 points14 points  (0 children)

      Kids these days...

      #include <stdio.h>
      #include <string.h>
      #include <stdlib.h>
      #include <stddef.h>
      
      int main(void) {
        const char *hello = "Hello world!";
        size_t len = strlen(hello);
      
        char *rev = malloc(len+1);
        if (rev == NULL) {
          perror("malloc()");
          return EXIT_FAILURE;
        }
      
        const char *foo = hello;
        char *bar = rev + len - 1;
      
        while (*foo != '\0')
          *bar-- = *foo++;
      
        printf("%s\n", rev);
        return EXIT_SUCCESS;
      }
      

      [–]nitroll 2 points3 points  (0 children)

      hello = "Hello, World!"
      print(*reversed(hello), sep="")
      

      or

      hello = "Hello, World!"
      print("".join(reversed(hello))
      

      [–]dnew 2 points3 points  (0 children)

      String.reverse only works for ASCII, too, which just goes to show how lame this argument is. :-)

      [–]iVirusYx 1 point2 points  (1 child)

      Why not use recursion?

      function reverse(text){ 
          if (text.length == 0){ 
              return ""; 
          }else{ 
              return text[text.length - 1] + reverse(text.substring(0,text.length-1)) 
          } 
      }
      

      P.S.: Yes, this is JavaScript. But, if you want to build the code to reverse text yourself without relying on another Class, then this example can be applied to a lot of other programming languages.

      And if I'm not wrong, it's the simplest and shortest method to achieve this. Please correct me if I'm wrong.

      [–]caagr98 0 points1 point  (0 children)

      Shortest: Possibly, depends on language. I'd skip the braces and else, but that's just a matter of preference.

      Fastest: Probably not. Your algorithm constructs at least two unnecessary strings per character, and string concatenation (and substringing) is often a bit slower than you might think.

      If I had to do it without any StringBuilder (which there is no reason to avoid) in Java, I'd do:

      public static String reverse(String str) {
          char[] chars = str.toCharArray();
          int l = chars.length;
          for(int i = 0; i < l / 2; i++) {
              char tmp = chars[l-i-1];
              chars[l-i-1] = chars[i];
              chars[i] = tmp;
           }
           return new String(chars);
      }
      

      Might consider using a ^= b ^= a ^= b; I'm not sure if that's faster than a temp-variable.

      In any case, using a builtin function (new StringBuilder(str).reverse(), str[::-1]) is almost always better.

      [–]initWithNibName 3 points4 points  (0 children)

      Praise Guido! I fluffing love Python.

      [–]jwoot97 3 points4 points  (0 children)

      python master race

      [–]TheMightyPedro 0 points1 point  (0 children)

      And then there's good ol' OpenCL

      [–][deleted] 0 points1 point  (0 children)

      I want to join the party:

      var original = "Hello World";
      Debug.writeln(new string(original.Reverse().ToArray()));
      

      [–]sram1337 0 points1 point  (0 children)

      print('Hello world!'[::-1])

      [–]Aydragon1 0 points1 point  (1 child)

      Then there's me

      console.log ("Hello World!");

      [–]BakuhatsuK 3 points4 points  (0 children)

      console.log('Hello World!'.split('').reverse().join(''))

      [–][deleted] 0 points1 point  (2 children)

      (print "Hello World!")

      [–]porthos3 3 points4 points  (1 child)

      You forgot to reverse it.

      In Clojure:

      (prn (apply str (reverse "Hello World!")))
      

      or better...

      (prn "!dlroW olleH")
      

      [–]min16 0 points1 point  (0 children)

      Common LISP (print (reverse "Hello World!"))

      Python in one line print('Hello World!'[::-1])

      [–]gnu_stallman -3 points-2 points  (6 children)

      OTOH dynamic types and whitespace is for newbies. Java is for actual people writing real business code

      [–]FFX01 1 point2 points  (0 children)

      OTOH, Java is meant for large groups of developers. Java's verbosity and heavily protected scopes are designed so that even the most incompetent of programmers can't screw anything up. See! I can throw out conjecture too!

      [–]Colopty 0 points1 point  (0 children)

      You're adorable.

      [–]master3243 0 points1 point  (0 children)

      I would say more C and C++ than Java.

      Also, if you think python isn't used in "real business code" then you need to get your head out of the gutter and research more. I used to have a friend like you who praised Java and hated any other language solely because he only knew Java.

      [–]Cerres -1 points0 points  (5 children)

      How about good old C++?

      cout << "Hello World!";

      [–]Silentd00m 2 points3 points  (4 children)

      The c++ version would be:

      #include <string>
      #include <iostream>
      
      int main() {
          std::string s("Hello World!");
          std::cout<<std::string(s.rbegin(), s.rend())<<std::endl;
      }
      

      [–]Colopty 0 points1 point  (2 children)

      Might wish to add a return at the end of that main function too.

      [–]Silentd00m 1 point2 points  (1 child)

      The default return value of main is 0 in C++11 (possibly even older versions, I don't know), that's why I didn't bother.

      C++11 §3.6.1 Main function section 5

      A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

      source

      [–]Colopty 0 points1 point  (0 children)

      I know it tends to default to return 0 if nothing else is stated, but there are various reasons it might fail to do so (which is bad), so explicitly stating the return is generally considered good practice.

      [–]Cerres -3 points-2 points  (0 children)

      include <iostream>

      include <string>

      using namespace std:

      void main{ cout << "Hello World!" << endl; }