Tidying and making a repeat column faster
Hi, I'm making an website and i need to format string so that every symbol is formatted into its appropiate counterpart like shown below:
how can i make this code far cleaner and faster?
11 Replies
How large is the string
it will be an url
i dont think it will be long but this code looks very ugly
the issue is there will be a lot of replace in here
string wont be that long, at least it isnt a paragraph
I'm not on my laptop but if the string Isn't that large as you are saying then I'd do it in a single pass by creating a new string instead of replacing multiple times . You would need a lengthy switch case for that ... That won't be much cleaner but can be faster
You can also use dictionary mapping perhaps in some way regex or what not
True
What do you mean by dictionary mapping
I cant get the gist of mapping atm
I also closed my laptop :p
So like:
Like this?
So you make a dictionary like this and and then iterate through the string and replace the keys with the values like this:
It's a bit cleaner right?
Nvm im derp
Yea it is cleaner
Yeah dictionary is great for such use cases
Didnt think about this approach at all, thanks for helping
Np 👍
Performance-wise I would not recommend this
It will allocate a new string for every replaced char
I would stick to
I don't know regex yet so I never said it was more performant but it was cleaner so. Ofc regex solutions can be better . It's doing the same thing as the original code .