Logo

Programming-Idioms

  • JS
  • Go

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.

import "strings"
i := strings.Index(x, y)

i is the byte index of y in x, not the character (rune) index.

i will be -1 if y is not found in x.
let i = x.indexOf(y);

This sets i to -1 if y is not found in x.
#include <string.h>
int i=(int)(x-strstr(x,y));

New implementation...