Logo

Programming-Idioms

  • C++
  • Java
  • Dart
  • Clojure
  • Lua

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 = 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.
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 = string.sub(s, 1, #prefix) == prefix

string:find is less efficient, as it has to search all of s
#include <string>
std::string prefix = "something";
bool b = s.compare(0, prefix.size(), prefix) == 0;

empty prefix is true
#include <string>
bool b = s.starts_with(prefix);

C++20
boolean b = s.startsWith(prefix);
var b = s.startsWith(prefix);
(require '[clojure.string :refer [starts-with?]])
(def b (starts-with? s prefix))

Uses java.lang.String.startsWith()
with Ada.Strings.Fixed;
B := Ada.Strings.Fixed.Index (S, Prefix) = S'First;

New implementation...