DEV Community

Cover image for How to Reverse a String

How to Reverse a String

Jake Z. on August 19, 2020

The only way to get better at solving algorithms and data structures is to power through a few. We covered the best ways to prepare in this lesson...
Collapse
 
pentacular profile image
pentacular

We know that strings can be thought of as character arrays-- that is, each element in the array is a single character.

This is incorrect, and why this is a non-trivial task.

A string represents text which is formed of graphemes, which are formed by combining character sequences in unicode.

Which means that in order to reverse a textual string properly you need to identify the graphemic units which need to be reordered, separate them, and then recombine.

Which means that you can't think of a string as being an array of characters if you want to process text properly in Javascript. :)

Collapse
 
diegolepore profile image
Diego Palacios Lepore

Interesting and accurate, arrays and strings are clearly not the same.

I think the confusion may come because both arrays and strings share some methods and properties with the same name, and we can do some "array-like" things, like:

length
concat()
str[0] -- character position access ( though, the correct approach should be str.charAt() )

Also, arrays are mutable and strings aren't. so we can't do this:

str[1] = 'stuff'

Also, when using the native constructor, for instance, new String('Sup dude') each character is numerically indexed (like arrays), but in this case, even though we're using the built-in native constructor, it is not creating a string, instead, it creates an object. So, when using the string properties - length, concat, etc - JS implicitly does this boxing for us( under the hood it uses the String() native ). So we need to do str.toString() in order to get the actual string.

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Those are language specific methods, in fact theoretically, strings have length while arrays have size, you can concat strings while you join arrays and string[i] breaks up on most languages for obvious reasons.

It's a comparison of whole different data structures where I don't want to involve at all (that's all already wrote about) but i feel the need to clarify this.

  • Also an array of chars is not the same than a string, if you want to sort, compare or change values from a string for a given output you'll need to cast it into a char array first. That's basic cryptography like Caesar's Cryptography for example.
Collapse
 
jacobjzhang profile image
Jake Z.

Thanks pentacular and Diego, these are really great points that I neglected to touch on. I'll add a bit into the tutorial and video to emphasize the distinctions.

Thread Thread
 
pentacular profile image
pentacular

You're welcome. :)

Thread Thread
 
diegolepore profile image
Diego Palacios Lepore

You did a great job Jake, we're all in this endless learning process! So keep up the good work man! :-)

Thread Thread
 
jacobjzhang profile image
Jake Z.

Appreciate the kind words!

Collapse
 
royalfig profile image
Ryan Feigenbaum

This is something I knew intuitively, but never thought of explicitly. Are there any resources you recommend that covers tips, tricks, gotchas for text processing in JS?

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Begin with JS data structures, then search for string related API on JavaScript. Note that JavaScript lacks static typing so sometimes you can call a method that deals with strings on a non-string data type (same with other data types and language pre-defined methods). At this point you don't know what it does in background for example when performing string split, but you can also dig deeper if you want.

Collapse
 
jacobjzhang profile image
Jake Z.

Yes, absolutely!

Collapse
 
rabbitzzc profile image
rabbitzzc

str.split('').reverse()

Collapse
 
wheatup profile image
Hao • Edited

BTW, this doesn't work for surrogate pairs:

'Hello World 🌎'.split('').reverse().join('')   // �� dlroW olleH

It's better to use spread syntax:

[...'Hello World 🌎'].reverse().join('')   // 🌎 dlroW olleH
Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

Does it always work correctly? I mean

[...'πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦']

Normally, I would rather trust this library -- npmjs.com/package/runes2

Collapse
 
rabbitzzc profile image
rabbitzzc

good

Collapse
 
gagandureja profile image
Gagan

python

print(str[::-1])
Collapse
 
terpinmd profile image
terpinmd

string.split().reverse().join()

Never reinvent the wheel :)

Collapse
 
estevanjantsk profile image
Estevan Jantsk

Ruby -> "string".reverse stonks

Collapse
 
jamesncox profile image
James Cox

Lol Ruby does some things so much simpler. Still it’s great to be able to do something manually!

Collapse
 
andrewbaisden profile image
Andrew Baisden

Plenty of ways to reverse a string thats a lot of wheels. πŸ˜‚

Collapse
 
jamesncox profile image
James Cox

This is the kind of thought process I absolutely need to improve. β€œHow can I optimize this procedure?” I need to better understand data structures to improve time/space complexity. Great read!!