// Example of using string functions from string.h library // strings can get a bit tricky and messy in C // It is easy to overflow buffers or lose our '\0' characters! #include #include #define MAX_LENGTH 100 int main(void) { // Declare an array to store a string char puppy[MAX_LENGTH] = "Boots"; printf("%s\n", puppy); // Copy the string "Finn" into the word array // strncpy will truncate the string if it is too long // this is safer than using strcpy which can cause buffer overflow // We use MAX_LENGTH - 1 as we need to be careful we still // have room for a '\0' character // even if we can't copy over the whole string // strncpy does not take care of that like fgets does strncpy(puppy, "Finn", MAX_LENGTH - 1); // We already have a '\0' at puppy[99] as we initialised it on // line 8 but lets do this anyway to be careful puppy[MAX_LENGTH - 1] = '\0'; printf("%s\n", puppy); // Find string length. It does NOT include '\0' in the length int len = strlen(puppy); printf("%s has length %d\n", puppy, len); // Declare an array to store a string char name[] = "Oscar"; // Use strcmp to compare 2 strings // It will return 0 if the strings are equal // A negative number if the first string < second string // A positive number if the first string > second string int comparison = strcmp("Oscar", name); printf("Are the 2 strings the same? %d\n", comparison); if (strcmp("Oscar", name) == 0) { printf("%s equals %s\n","Oscar", name); } else if (comparison < 0 ){ printf("%s < %s\n", "Oscar", name); } else { printf("%s > %s\n", "Oscar", name); } comparison = strcmp(name, "Edgar"); printf("Are the 2 strings the same? %d\n", comparison); if (comparison == 0) { printf("%s equals %s\n", name, "Edgar"); } else if (comparison < 0 ){ printf("%s < %s\n", name, "Edgar"); } else { printf("%s > %s\n", name, "Edgar"); } // Declare an array to store a string char city[MAX_LENGTH]; printf("\nType in the name of a city: "); // Read in a string fgets(city, MAX_LENGTH, stdin); len = strlen(city); if (city[len - 1] == '\n') { city[len - 1] = '\0'; } // Use strcmp to compare 2 strings if (strcmp("Sydney", city) == 0) { printf("I live in Sydney!\n"); } return 0; }