/* * Program to find length of string, several ways. * Also illustrates use of strcpy to copy a string and * strcmp to compare two strings. */ #include #include #define SIZE 80 /* operate on string using array index */ int strlen_array(char s[]) { int count = 0; while (s[count] != '\0') { count+=1; } return count; } /* operate on string using pointer */ int strlen_pointer(char *s) { char *p = s; while (*p != '\0') { ++p; } return p-s; } /* operate on string using pointer and recursion */ int strlen_recursive(char *s) { if (*s == '\0') { return 0; } else { return 1 + strlen_recursive(s+1); } } int main(void) { printf("enter line\n"); char line[SIZE]; fgets(line, SIZE, stdin); /* was the line too long? */ char *endline = strchr(line, '\n'); if (endline == NULL) { printf("line too long\n"); return 1; } *endline = '\0'; printf("line is '%s'\n", line); printf("strlen_array %d\n", strlen_array(line)); printf("strlen_pointer %d\n", strlen_pointer(line)); printf("strlen_recursive %d\n", strlen_recursive(line)); printf("library strlen %d\n", (int) strlen(line)); char copy[SIZE]; strcpy(copy, line); printf("copy is '%s'\n", copy); if (strcmp(copy, line) == 0) { printf("equal\n"); } else { printf("not equal\n"); } return 0; }