0

Is this a bad way to reverse a string? I'm still somewhat of a beginner and I've read that some companies look for how you would reverse a string? So here's how I did it, and it works but would companies look down on this? I'm in my second semester of a first year CS major at a University. Thanks in advance!

String reversedWord = "";
    for (int i = 0; i < word.length(); i++)
    {
        char temp = word.charAt(word.length()-1-i);
        reversedWord = reversedWord + temp;
    }
    System.out.println(reversedWord);
  • 3
    You probably should at least use a `StringBuilder`. – Sirko Mar 11 '18 at 08:20
  • 1
    It's always best not to re-invent the wheel. `StringBuilder` has a `reverse` method. – Dawood ibn Kareem Mar 11 '18 at 08:22
  • Adding on to a `String` in a loop is inefficient, because the whole string is copied each time. That's why we have `StringBuilder` – khelwood Mar 11 '18 at 08:22
  • see also https://stackoverflow.com/questions/5234147/why-stringbuilder-when-there-is-string – dovid Mar 11 '18 at 08:23
  • Companies ask you to for trivial things in interviews to see how your brain works. You could first solve it with `StringBuilder.reverse()`, but they'd most likely want a manual version and explanations on why you'd write it that way. – Kayaman Mar 11 '18 at 08:26
  • I see, this is my first time seeing StringBuilder (as I am merely still a beginner) our prof has never showed us anything outside the basic classes and always tend to give us assignments doing it this style. Thanks for all the help! Sorry for the duplicate post! – Jason Li Mar 11 '18 at 08:42

0 Answers0