Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #167 Trim prefix

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

String t = s.replaceFirst("^" + p, "");

This works if p doesn't contain any regexp control characters
import static java.util.regex.Pattern.quote;
String t = s.replaceFirst('^' + quote(p), "");
int i = s.indexOf(p), n = p.length();
t = i == 0 ? s.substring(n) : s;
#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...