How to reverse a string?

Take a string like +54321, how to reverse it to +12345?

In Bash:

echo +54321 | rev

12345+


rev is not self explanatory.

How would you suggest to do that in a self explanatory way but with the least amount of code?

I was thinking about C, Python, Perl, Java and C#, but I never worked with any of these languages.

Personally I would prefer an interpreted language like Bash or JavaScript over a compiled language but please feel free to share your most preferred way with either.
I didn’t find a way which I would consider “both clear and self explanatory” to this with the current release of JavaScript.

Javascript is easy. Convert it to a string array, reverse it and change it back to a string. Can do it in one chained line…

let number = "12345";
let reversed = number.split('').reverse().join('');

console.writeline("before");
console.writeline(number);
console.writeline("after");
console.writeline(reversed);

image

MySQL has got a function that reverses a string. I don’t know if it’s a standard function across all database servers or if just MySQL has it. @r937 would know, as he’s probably used every database software that’s ever been released.

The very concept of a “string array” is something I personally would choose to step away from pedagogically, but if you meant to say “an array containing at least one string” then that is something I would gladly work with.

Anyway, I personally don’t find split() method very self explanatory and therefore I have mentioned languages like C, Python, Perl, Java, and C# before mentioning JavaScript - they might contain better self explanatory methods for this task.

A string is an array of characters, in many languages.

3 Likes

I dont know that you’re going to get a more self-explanatory function name than “reverse”. It takes something, and gives you that thing reversed. Which… is exactly what you asked for.

MariaDB/MySQL (4.0+) has a REVERSE() function,
as does SQL Server (2008+),
PHP has strrev, which admittedly is not as clear of a name,
C# you’d need to make an array out of the string to use the Array.reverse function,
Python doesnt really have a string reversing function, but can reference the string as an array of characters, so you can use the odd looking construction "Hello World"[::-1] to walk backwards through the array…

1 Like

No, I meant an array made out of a string - that’s what a string array is. The C# implementation calls it a a character array but you have to split it, use an array process, then put it back together…

        static string ReverseString(string s)
        {
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }

split() does exactly what it calls it. The parameter is used to determine what to split by but if you pass a blank like I did, it splits it character by character. If you put a split(‘,’), it would split the string into the array based on the commas in the string.

join(‘’) does the exact opposite. It takes the array and does a string concatenation to build on long string and uses the parameter in between each array element. Since I passed nothing, it puts nothing between each element.

I think that what I meant to ask is how would you suggest to reverse a string like +54321 without a method such as Bash rev or JavaScript split('').reverse().join('');.

thanks for the kind words ;o)

no, i don’t think it’s a standard sql function

postgresql has reverse() too, though, and it’s usually close to the standard

I was reading an article yesterday, that MySQL has introduced javascript support. I believe this is only available in the paid for versions. Thought it was interesting though.

https://blogs.oracle.com/mysql/post/introducing-javascript-support-in-mysql

1 Like

…why would you not want to use a method?

You’re using echo, and thats a method (function)…

I don’t understand the reluctance to use a tool available to you.

I want to understand how it can be done with languages in a less abstract way, to perhaps learn a pattern of how to do it less abstractly if I need to do that in the future, for whatever reason.

There’s… not going to be a ‘less abstract way’ than an atomic REVERSE() function, that doesn’t involve walking the string like an array in one form or another.

You rejected the idea of the string as an array, and you reject the idea of an atomic function.

What more do you expect people to tell you?

You’ve driven up to a T junction into a festival square full of people. You want to get to the other side of the square. You dont want to go left, and you dont want to go right.

You say reverse it to +12345 but then your example reverses it to 12345+.

You could use a loop that switches each character, between the beginning and the end, that begins at the first (or last) character then goes to the middle character. If there are an odd number of characters then the middle character remains in the middle. Many developers might move all characters but it is only necessary to move half of them. This algorithm can be used in all languages (that you list at least). The problem with writing code such as that is that it is inefficient for both the hardware and people.

I would interpret string array as an array of strings. I think the term relevant here is array of characters, as in ToCharArray.

In C, strings and character arrays are exactly the same.

You are being theoretical rather than practical. People around here tend to avoid discussions of impractical solutions.

Not so much impractical but inefficient. Why not use ALL of the tools available to you? It’s like trying to use a standard hammer to drive in a railroad spike when you have access to a sledgehammer. Why work harder than you need to?

The less abstract way would be to perform the functions already provided by the language you’re using.

Using loops and substrings or indexes (depending on if you convert it to an array which almost ALL the languages do) to pull the single character from a position (last to first in the loop) and appending it to a string.

OR

Just use the methods native to the language which are intended to make your life easier…

My intended meaning of impractical is that it is inefficient.

Certainly.

I think you know that the compilers would use libraries or generate code that does that. Therefore the solution(s) provided by the language would likely be more efficient than any code we would write to do it.

1 Like

You say reverse it to +12345 but then your example reverses it to 12345+.

That’s the closest I got with Bash rev; I don’t know why the + wasn’t reversed as well. Do you have an idea?

You are being theoretical rather than practical. People around here tend to avoid discussions of impractical solutions.

I find this comment flaming and anyway redundant.
I have shown the best ways I know and ask for more.
In my opinion, that’s practical enough.
I you have better ways, please do enrich us.

@DaveMaxwell I think I understand this code better know. Your review of the three steps explanation I wrote below would be most appreciated !

let myString = "12345+";
let reversed = myString.split('').reverse().join('');
console.log(reversed);

+54321

Three steps explanation of this code:

  1. Split a string to a plethora of individual characters.
  2. Take each individual character and put it in the end of the plethora of individual characters.
  3. Join the reversed plethora of individual characters to a string.

A didactic explanation in your opinion? :slight_smile:

  1. I mean… it’s not a “plethora”, its an organized array of a fixed size equal to the length of the original string. We’re not just throwing out extra characters for the sake of it :stuck_out_tongue:
  2. Reversing an array… can i suppose be thought of it as such… basically it’s taking the indexes of that array and swapping them; so 0 swaps with array.length - 1 (the last index in the array), 1 swaps with -2, etc.
    It’s more efficient to do a pair of swaps than it is to do “put 0 at the end of the array. Now re-index the whole array. Now repeat until you’ve done this array length times”
  3. Again, it’s a fixed and known size, but yes, thats the gist.