IndexOf v0.1.0

Source
Returns the offset of the first occurrence of a substring.

Package: Text

Signature

func IndexOf(self, needle: String) -> int;

Parameters

NameTypeDescription
needleStringThe bytes to search for.

Returns

The byte offset of the first match, or -1 when there is none. The empty needle matches at the front and reports 0, and a needle longer than the string never matches.

The offset is in bytes, so it can be handed straight to Substring, and it can land inside a multi-byte UTF-8 sequence when the needle does.

The scan is the plain one — every starting offset is tried in turn — so the worst case costs the product of the two lengths. Reach for Contains when only the answer matters and not the position.

Example

import Text::String;

func Main() -> int {
    var text = String::From("Hello, Rux!");
    var needle = String::From("Rux");
    var missing = String::From("C");

    text.IndexOf(needle);  // 7
    text.IndexOf(missing); // -1

    missing.Free();
    needle.Free();
    text.Free();
    return 0;
}

See also

  • String — the string type
  • Contains — the same search when the position does not matter
  • Substring — copy the bytes the offset points at
  • StartsWith — the cheaper test when the match has to be at the front