/* strings.c Jeff Ondich, 6 Jan 2022 Modified by Tanya Amert for Fall 2023 This program demonstrates the use of C strings (i.e., null-terminated char arrays), including a couple standard library string functions and passing strings as parameters to functions. Compile as usual: gcc -Wall -Werror -g -o strings strings.c Run with two command-line arguments: ./strings apple banana */ #include #include // It is best to avoid magic numbers, so the maximum char-array size // is "pound-defined" here. #define BUFFER_SIZE 200 void reverse_string(char *string); // Demonstrates different things you can do with strings // (represented as null-terminated character arrays) in C. int main(int argc, char *argv[]) { // Parse the command line if (argc != 3) { fprintf(stderr, "Usage: %s string1 string2\n", argv[0]); return 1; } char *string1 = argv[1]; char *string2 = argv[2]; // Game 0: Build a null-terminated string manually printf("===== string game #0 =====\n"); char buffer[BUFFER_SIZE]; buffer[0] = 'd'; buffer[1] = 'o'; buffer[2] = 'g'; buffer[3] = '\0'; // try replacing this with a different character buffer[4] = 'c'; buffer[5] = 'a'; buffer[6] = 't'; printf("Here's your manually created string: \"%s\"\n", buffer); printf("\n"); // Game 1: Report the lengths of the strings printf("===== string game #1 =====\n"); printf("Length of \"%s\": %ld\n", string1, strlen(string1)); printf("Length of \"%s\": %ld\n", string2, strlen(string2)); printf("\n"); // Game 2: Report the lengths of string1 manually printf("===== string game #2 =====\n"); int length = 0; while (string1[length] != '\0') { length++; } printf("Length of \"%s\": %d\n", string1, length); printf("\n"); // Game 3: Compare the strings printf("===== string game #3 =====\n"); int comparison = strcmp(string1, string2); if (comparison < 0) { printf("\"%s\" comes before \"%s\".\n", string1, string2); } else if (comparison > 0) { printf("\"%s\" comes after \"%s\".\n", string1, string2); } else { printf("\"%s\" and \"%s\" are identical.\n", string1, string2); } printf("\n"); // Game 4: concatenate the strings printf("===== string game #4 =====\n"); strncpy(buffer, string1, BUFFER_SIZE); buffer[BUFFER_SIZE - 1] = '\0'; strncat(buffer, string2, BUFFER_SIZE - 1); buffer[BUFFER_SIZE - 1] = '\0'; printf("Your strings concatenated: \"%s\"\n", buffer); printf("\n"); // Game 5: Reverse the result printf("===== string game #5 =====\n"); reverse_string(buffer); printf("Your concatenated string, reversed: \"%s\"\n", buffer); printf("\n"); return 0; } // Reverses the specified null-terminated string in-place. // // Parameters: // - string: pointer to a character array // // Returns: // - nothing; modifies string in place void reverse_string(char *string) { int high_index = (int)(strlen(string)) - 1; int low_index = 0; while (low_index < high_index) { char saved_char = string[low_index]; string[low_index] = string[high_index]; string[high_index] = saved_char; low_index++; high_index--; } }