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.csize_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:
- Iterate through
swith indexi. - For each
s[i], iterate through every character inrejectwith indexj. - If
s[i]matches anyreject[j], returni(the length of the safe prefix). - 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.