Logo

Programming-Idioms

  • Haskell
  • VB
  • Go

Idiom #167 Trim prefix

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

import "strings"
t := strings.TrimPrefix(s, p)
import qualified Data.Maybe as Maybe
import qualified Data.List as List
t = Maybe.fromMaybe s $ List.stripPrefix p s

List.stripPrefix returns Nothing if s does not start with p and returns Just strippedString if it starts with p.
Maybe.fromMaybe makes it so that we return s if the result is Nothing, or the strippedString if the result is
Just strippedString.
#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...