How to implement the strcmp function in C

1 Answer

0 votes
#include <stdio.h>

int strcmp(const char* s1, const char* s2) {
	// compare s1 and s2
	for (; *s1 == *s2; s1++, s2++)
		if (*s1 == '\0') {
			return 0;
		}
	return *(unsigned char*)s1 < *(unsigned char*)s2 ? -1 : +1;
}

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

	printf("%d", strcmp(str1, str2));

	return 0;
}





/*
run:
         
0
      
*/

 



answered Dec 16, 2022 by avibootz

Related questions

2 answers 804 views
1 answer 173 views
2 answers 275 views
1 answer 86 views
86 views asked Jun 10, 2025 by avibootz
1 answer 134 views
1 answer 131 views
1 answer 102 views
102 views asked Aug 2, 2024 by avibootz
...