belteconti
Hey! Hope everyone is doing well.
I basically want to replace a character in a string at a specific index. Now, I can’t really convert this to a list using String.graphemes and then recursing over it cause the indexes I am getting is from a list as well and both are of different sizes.
In simpler terms, I have the following list called mylist with the values: [3, 7] and a string called str with characters 123+*12-+3456. Now, the contents inside mylist are the indexes at which I want to replace the characters in the string.
In other words, for the above example, I want to replace the character at index 3, which is +. Similarly, I want to replace the character at index 7. The final string I would get is 123*12+3456.
I tried using a combination of String.at and String.replace, however, the latter replaces all the characters. Is there an efficient way of doing this?
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #elixirconf-eu
- #metaprogramming
- #hex










Showing Posts 1 to 6- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
stefanchrobot
I would write a recursive function that goes through the string once and replaces the character as it goes. Something like (assuming the indices are sorted):
belteconti
This is brilliant! Thank you so much
fuelen
This is the first thing that comes to my mind
hauleth
eksperimental
This one is just for fun.
Probably works better with lists (so it does not have to iterate over the whole list twice), and big ones,
Uses Enum.while, keeping a copy of the remaining chars, and as soon as your indexes’ list is empty it returns.
werkzeugh
here’s my take on it