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 821 views
1 answer 185 views
2 answers 292 views
1 answer 93 views
93 views asked Jun 10, 2025 by avibootz
1 answer 144 views
1 answer 148 views
1 answer 114 views
114 views asked Aug 2, 2024 by avibootz
...