Logo

Programming-Idioms

  • Java
  • Pascal

Idiom #96 Check string prefix

Set the boolean b to true if string s starts with prefix prefix, false otherwise.

Are the first characters of s equal to this prefix?
b = string.sub(s, 1, #prefix) == prefix

string:find is less efficient, as it has to search all of s
function startswith(text, prefix)
    return text:find(prefix, 1, true) == 1
end

b = startswith(s, prefix)

startswith is not built-in, so you must define it yourself.
find is a built-in method for strings.
b = s:find(prefix, 1, true) == 1

The 4th arg true for "plain" is important to turn off the pattern matching facilities: no characters in prefix are considered magic.
boolean b = s.startsWith(prefix);
b := pos(prefix, s) = 1;

Strings in Pascal start at index 1
with Ada.Strings.Fixed;
B := Ada.Strings.Fixed.Index (S, Prefix) = S'First;

New implementation...