Logo

Programming-Idioms

  • Kotlin
  • C++
  • Python
  • Rust
  • PHP
  • Scala
  • C

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?
#include <stdbool.h>
#include <string.h>
bool b = !strncmp(s, prefix, sizeof(prefix)-1);
val b = s.startsWith(prefix)
#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
b = s.startswith(prefix)
let b = s.starts_with(prefix);
$b = (bool) preg_match('#^http#', $s);

But what about a variable $prefix (not a constant) ?
val b = s.startsWith(prefix)
with Ada.Strings.Fixed;
B := Ada.Strings.Fixed.Index (S, Prefix) = S'First;

New implementation...