Logo

Programming-Idioms

  • D
  • Ada
  • Rust
  • Java
  • Lua

Idiom #167 Trim prefix

Create the string t consisting of the string s with its prefix p removed (if s starts with p).

local t = (s:sub(0, #p) == p) and s:sub(#p+1) or s
import std.string;
string t = s.chompPrefix(p);
let t = if s.starts_with(p) { &s[p.len()..] } else { s };
let t = s.trim_start_matches(p);

Warning: this would remove several leading occurrences of p, if present.
See strip_prefix to remove only one occurrence.
let t = s.strip_prefix(p).unwrap_or(s);

Removes p at most once.
int i = s.indexOf(p), n = p.length();
t = i == 0 ? s.substring(n) : s;
import static java.util.regex.Pattern.quote;
String t = s.replaceFirst('^' + quote(p), "");
String t = s.replaceFirst("^" + p, "");

This works if p doesn't contain any regexp control characters
#include <string.h>
size_t l = strlen(p);
const char * t = strncmp(s, p, l) ? s : s + l;

strlen computes the prefix length and strncmp returns zero if the first l characters match

New implementation...