CSC161 2010F, Class 34: Strings Overview: * Questions on Exam 2 * About strings. * Important string functions. * Thinking like a C programmer. * Lab. Admin: * Reminder: NaNoWriMo and PragProWriMo start today. * What's a little more stress? * EC for MD's noontime talk. "The Hinkle Transform in French" (Free pizza and soda, too!) (Prereq: Linear Algebra) * Stories from Friday's lunch. * Reading for Tuesday: K&R 5.6-5.9. Questions on Exam 2: * How do I search for a man page related to something? man -k THING * How do I search within a man page /THING * #ifdef SOMETHING is just asking if SOMETHING is defined (right?) and the -DSOMETHING flag is saying that SOMETHING is defined (right?) - but where is it defined or where/how should it be defined so that it's only defined when we want to compile the unit tests? Does it have to have a value where it's defined and any other value means it's not defined? * Two related issues: "Is it defined?" and "What is it defined as?" * Is it defined? Check with #ifdef Define with #define FOO - In code or -DFOO - CFLAGS * What is its value? Check with #if EXP Define with #define FOO VALUE - In code or -DFOO=VALUE - CFLAGS * How do I build random arrays of sizes 1 through 10? for (size = 1; size <= 10; size++) { int values[size]; for (i = 0; i < size; i++) values[i] = rand (); } // for (size) * How do I find the length of an array? * Generally, you can't. * So, in C, you usually pass the size along as an extra parameter. Strings: * A string is an array of characters That ends with character 0. (aka null) (aka nul) * In C, arrays are a lot like pointers * So strings are also pointers to characters (more traditionally) char str1[] = "Hello"; char str2[6] = "Hello"; char *str3 = "Hello"; What's the difference? * char *str3 = "Hello" makes str3 point to a *constant* string * You can change individual characters in str1 and str2, but not str3 * You can make str3 point to other things str3 = "Goodbye"; // LEGAL str1 = "Goodbye"; // ILL EAGLE String Functions: * Find the length: strlen (char *str) * Copy one string to another: strcpy (char *target, char *source) * Append to a string: strcat (char *target, char *source) * Copy one string to another: strncpy (char *target, char *source, int n) * Append to a string: strncat (char *target, char *source, int n) * Look at /usr/include/string.h for more Thinking like a C programmer * How do we copy from source to target? (strcpy?) Repeat until you reach the end of the string copy the current character from target to current character in source Move on to the next character in each while (*t++ = *s++) ; Lab