Skip to main content

ft_strcspn — Span Until Rejected Character

Allowed functions: none

Reproduce exactly the behavior of the function strcspn (man strcspn).

size_t	ft_strcspn(const char *s, const char *reject);

Solution

Download ft_strcspn.c
size_t ft_strcspn(const char *s, const char *reject) {

size_t i;
size_t j;

i = 0;

while (s[i]) {
j = 0;

while (reject[j]) {

if (s[i] == reject[j])
return i;
j++;
}
i++;
}

return i;
}

How It Works

Goal: Find the length of the initial segment of s that contains no characters from reject.

Approach: For each character in s, scan all characters in reject; return immediately on a match.

Step by step:

  1. Iterate through s with index i.
  2. For each s[i], iterate through every character in reject with index j.
  3. If s[i] matches any reject[j], return i (the length of the safe prefix).
  4. If no rejected character is ever found, return the full length of s.

Key concept: Nested loops for cross-checking two strings, with an early return for efficiency.