CSC195, Class 16: Strings Overview * Representing strings * Key string procedures * Lab Notes: * I revised the structs lab to reflect questions and discussion * Cool talk on Fermat's little theorem today at 4:30. Why go out in the snow when you can hear about Math? Extra credit for going. * Cool concert next Friday at Bob's. Extra credit for going. http://www.cs.grinnell.edu/~kuper/ * Read Chapters 5 for next week * Question from last lab. typedef union lemur { int i; struct { char b1,b2,b3,b4; } bytes; } lemur; (define exponent (lambda (base power) (cond ((zero power) 1) ((even? power) (square (exponent base (/ power 2)))) (else (* base (exponent base (- power 1))))))) O(log_2(n)) * Question from last lab. typedef union lemur { int i; struct { char b1,b2,b3,b4; } bytes; } lemur; What does the code above mean? * Create a data structure that holds either (1) an integer or (2) a structure. The substructure holds four characters and is named bytes. Why? * An easy way to process individual bytes in an integer. Why is it a bad idea? * Sometimes works * Sometimes doesn't * I.e. NOT PORTABLE ---------------------------------------- Questions about strings? A string is a NULL-TERMINATED array of characters Libraries of string operations: * strcpy(char *destination, char *source); copies to destination from source * strcpy(char *destination, char *source, int n); copies first n characters of source to destination * strlen(char *str) Find the length of a string * strcat(char *destination, char *source); Shoves source at the end of destination What if source is longer than destination in strcpy? * Explore it experimentally! * It's up to you as programmer to decide whether it's safe. ------------------------------------------------------------ Reflection * Write a simple program in which the two printf statements are different #include main() { char antelope[] = "%d"; printf("Bare: "); printf(antelope); printf("\n"); printf("Alternative: "); printf("%s", antelope); exit(0); } /* main() */ * Moral: The first argument to printf is *always* a pattern, even if it's a variable. So: You can build patterns on the fly [EB]. * Why is it okay to write char antelope[10] = "antelope"; but not char antelope[8] = "antelope"; * Observation: If you initialize the string when you create it, you need not specify a size (but you may) char antelope[] = "antelope"; * For those who get to the last question. The Name Game is a song popularized by Shirley Ellis. For "Larry" it goes Larry Larry Bo Barry Banana Fanna Fo Farry Fe Fi Mo Marry, Larry