Logo

Programming-Idioms

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

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.

I=index(x,y)
#include <string.h>
int i=(int)(x-strstr(x,y));
#include <string>
int i = x.find(y);
var i = x.IndexOf(y);
import std.algorithm;
auto i = x.countUntil(y);
var i = x.indexOf(y);
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
import "strings"
i := strings.Index(x, y)
import Data.List
Just i <- (y `isPrefixOf`) `findIndex` (tails x)
let i = x.indexOf(y);
int i = x.indexOf(y);
i = x:find(y)
$i = mb_strpos($x, $y, 0, 'UTF-8');
i := Pos(y, x);
$i = index($x, $y);
i = x.find(y)
i = x.index(y)
let i = x.find(y);

New implementation...