How to implement the strcspn function in C

1 Answer

0 votes
#include <stdio.h>

size_t strcspn_(const char* s1, const char* s2) {
	// find index in s1 of first s2[i] in s1
	const char* p1, * p2;

	for (p1 = s1; *p1 != '\0'; p1++)
		for (p2 = s2; *p2 != '\0'; p2++)
			if (*p1 == *p2) // *p2 = "am" *p1 = "ammin"
				return p1 - s1;
	return p1 - s1;
}

int main() {
	const char str1[32] = "c programming";
	const char str2[32] = "am";

	printf("%zu", strcspn_(str1, str2));

	return 0;
}




/*
run:
    
7
    
*/




 



answered Dec 18, 2022 by avibootz

Related questions

1 answer 184 views
184 views asked Jun 10, 2025 by avibootz
1 answer 232 views
1 answer 247 views
1 answer 185 views
185 views asked Aug 2, 2024 by avibootz
2 answers 337 views
337 views asked Jan 7, 2024 by avibootz
...