belteconti

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?

Showing Posts 1 to 6

stefanchrobot

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):

defmodule Replacer do
  def replace(string, indices) do
    replace(string, indices, 0, "")
  end

  def replace(string, [], _current, acc) do
    acc <> string
  end

  def replace(string, [index | indices], current, acc) do
    case String.next_grapheme(string) do
      nil ->
        acc

      {next, rest} ->
        if index == current do
          replace(rest, indices, current + 1, acc <> "_")
        else
          replace(rest, [index | indices], current + 1, acc <> next)
        end
    end
  end
end
belteconti

belteconti OP

This is brilliant! Thank you so much

fuelen

fuelen

This is the first thing that comes to my mind

iex(11)> indices = [3, 7]                                                                                                                                                
[3, 7]
iex(12)> replace_by = "_"                                                                                                                                                
"_"
iex(13)> "123+*12-+3456"                                                                                                                                                 
"123+*12-+3456"
iex(14)> |> String.graphemes()                                                                                                                                           
["1", "2", "3", "+", "*", "1", "2", "-", "+", "3", "4", "5", "6"]
iex(15)> |> Enum.with_index()                                                                                                                                            
[
  {"1", 0},
  {"2", 1},
  {"3", 2},
  {"+", 3},
  {"*", 4},
  {"1", 5},
  {"2", 6},
  {"-", 7},
  {"+", 8},
  {"3", 9},
  {"4", 10},
  {"5", 11},
  {"6", 12}
]
iex(16)> |> Enum.map(fn {value, index} -> if index in indices, do: replace_by, else: value end)                                                                          
["1", "2", "3", "_", "*", "1", "2", "_", "+", "3", "4", "5", "6"]
iex(17)> |> to_string()
"123_*12_+3456"
hauleth

hauleth

defmodule Replacer do
  def replace(string, indices, replacement \\ ""),
    do: do_replace(string, Enum.sort(indices), 0, replacement)

  defp do_replace(<<>>, _, _, _), do: <<>>
  defp do_replace(<<_::utf8>> <> rest, [idx | indices], idx, replacement),
    do: replacement <> do_replace(rest, indices, idx + 1, replacement)
  defp do_replace(<<c::utf8>> <> rest, indices, idx, replacement),
    do: <<c::utf8>> <> do_replace(rest, indices, idx + 1, replacement)
end
eksperimental

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.

index_list = [3, 7]
string = "123+*12-+3456"
replacement = "X"

replacement =
  if replacement == "" do
    nil
  else
    replacement |> String.to_charlist() |> hd()
  end
  
charlist = String.to_charlist(string)

{first, second} = 
  Enum.reduce_while(charlist, {0, index_list, charlist, []}, fn
       # we are done
       _char, {_current_index, [], rest_charlist, acc} ->
          {:halt, {acc, rest_charlist}}

       # replace
       _char, {current_index, [current_index | rest_index_list], rest_charlist, acc} ->
        {:cont, {
          current_index + 1,
          rest_index_list,
          tl(rest_charlist),
          if replacement do
            [replacement | acc]
          else
            acc
          end
        }}

       # move forward
       char, {current_index, index_list, rest_charlist, acc} ->
        {:cont, {current_index + 1, index_list, tl(rest_charlist), [char | acc]}}
     end)

Enum.reverse(first, second) |> List.to_string()
werkzeugh

werkzeugh

here’s my take on it

iex(2)> "loosing" |> String.graphemes() |> put_in([Access.at(3)], "t") |> Enum.join()

"looting"
— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews