// A simple example of strings in C // Illustrates: // declaration of strings // strings are array of characters // strings are zero-terminated // formatted output and format specifiers %s, %c, %d // // Compile: gcc simplestrings.c // Run: a.out // Optional Compile: gcc -o simplestrings simplestrings.c // Optional Run: simplestrings #include int main() { // Declare a string. Notice the location of the [] char aStr[] = "ABC"; // Print the format string, substituting value of aStr for %s // \n is an escape sequence that prints a newline character printf("String variable: '%s'\n", aStr); // Print the characters of array aStr as individual characters printf("First character: '%c'\n", aStr[0]); printf("Second character: '%c'\n", aStr[1]); printf("Third character: '%c'\n", aStr[2]); // Now print the characters of the array aStr using a loop // Also print value of index i (%d prints a decimal) int i; for (i=0; i < 3; i++) { printf("Character %d: '%c'\n", i, aStr[i]); } printf("\n"); // Print a blank line // Strings are zero-terminated i = 0; while (aStr[i] != 0) // Notice the ending condition { printf("Character %d: '%c'\n", i, aStr[i]); i++; } } /* Output: String variable: 'ABC' First character: 'A' Second character: 'B' Third character: 'C' Character 0: 'A' Character 1: 'B' Character 2: 'C' Character 0: 'A' Character 1: 'B' Character 2: 'C' */