Logo

Programming-Idioms

  • C
  • D
  • Pascal

Idiom #167 Trim prefix

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

uses StrUtils;
if AnsiStartsStr(p, s) then 
  t := copy(s, length(p)+1, length(s)-length(p))
else
  s := t;
#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
import std.string;
string t = s.chompPrefix(p);
#include <string>
std::string t = s.starts_with(p) ? s.substr(p.size()) : s;

New implementation...