Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Elixir

Idiom #62 Find substring position

Set i to the first position of string y inside string x, if exists.

Specify if i should be regarded as a character index or as a byte index.

Explain the behavior when y is not contained in x.

defmodule Dry do
  def indexOf(x, y, default \\ -1) do
    case String.split(x, y, parts: 2) do
      [head, _] -> String.length(head)
      [_] -> default
    end
  end
end

See "Elixir Lang Core" [Doc] for discussion on integration into core Elixir
TL;DR NO
# Outside of module
case String.split(haystack, needle, parts: 2) do
[head, _] -> String.length(head)
[_] -> -1
end
#include <string.h>
int i=(int)(x-strstr(x,y));

New implementation...