/* * Program to compute length of strings various ways, as a silly * example of working with strings. * * Also shows some other things related to strings. */ #include #include /* compute length using array and indices */ int string_length_array(char s[]) { int i = 0; while (s[i] != '\0') { ++i; } return i; } /* compute length using pointers */ int string_length_ptr(char *s) { char *p = s; while (*p != '\0') ++p; /* p points to \0 */ return p - s; } /* compute length using pointers and recursion */ int string_length_recurs(char *s) { if (*s == '\0') { return 0; } else { return 1 + string_length_recurs(s+1); } } /* try functions above and print input, output */ void test(char *s) { printf("string '%s'\n", s); printf("length using lib %d\n", (int) strlen(s)); // cast is sloppy printf("length using array %d\n", string_length_array(s)); printf("length using ptr %d\n", string_length_ptr(s)); printf("length using recurs %d\n", string_length_recurs(s)); printf("\n"); } /* main program */ int main(void) { test("hello world"); test("1234"); test(""); /* try comparisons */ char s1[] = "hello"; char s2[] = "hello"; printf("s1 == s2? %c\n", (s1 == s2) ? 'y' : 'n'); printf("s1 equals s2 using strcmp? %c\n", (strcmp(s1, s2) == 0) ? 'y' : 'n'); return 0; }