fork download
  1. #include <stdio.h>
  2.  
  3. // 1. String Length (Exercise 8.30)
  4. size_t my_strlen_arr(const char *s) {
  5. size_t i = 0;
  6. while (s[i] != '\0') i++;
  7. return i;
  8. }
  9. size_t my_strlen_ptr(const char *s) {
  10. size_t len = 0;
  11. while (*s++) len++;
  12. return len;
  13. }
  14.  
  15. // 2. String Copy (Exercise 8.28)
  16. void my_strcpy_arr(char *s1, const char *s2) {
  17. int i = 0;
  18. while ((s1[i] = s2[i]) != '\0') i++;
  19. }
  20. void my_strcpy_ptr(char *s1, const char *s2) {
  21. while ((*s1++ = *s2++));
  22. }
  23.  
  24. // 3. String Compare (Exercise 8.29)
  25. int my_strcmp_arr(const char *s1, const char *s2) {
  26. int i = 0;
  27. while (s1[i] == s2[i] && s1[i] != '\0') i++;
  28. return s1[i] - s2[i];
  29. }
  30. int my_strcmp_ptr(const char *s1, const char *s2) {
  31. while (*s1 == *s2 && *s1 != '\0') {
  32. s1++; s2++;
  33. }
  34. return *s1 - *s2;
  35. }
  36.  
  37. int main(void) {
  38. char str1[50];
  39. char str2[] = "Hello";
  40. char str3[] = "World";
  41.  
  42. my_strcpy_ptr(str1, str2);
  43. printf("Copied string: %s\n", str1);
  44. printf("Length of string: %zu\n", my_strlen_arr(str1));
  45. printf("Comparison result: %d\n", my_strcmp_ptr(str2, str3));
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
Copied string: Hello
Length of string: 5
Comparison result: -15