240 likes | 404 Views
B Smith: Make use of the debugger for showing array address?. B Smith: Several slides from James Knight, cs156, Lecture 5. B Smith: 10/21 and 10/24: Took 2 classes along with a quiz. Still choppy in spots, but good forewarnings of commong problems they might see. Rate 3/4.
E N D
B Smith: Make use of the debugger for showing array address? B Smith: Several slides from James Knight, cs156, Lecture 5 B Smith: 10/21 and 10/24: Took 2 classes along with a quiz. Still choppy in spots, but good forewarnings of commong problems they might see. Rate 3/4 Math 130Introduction to ComputingCharacter Strings - 2Lecture # 18 B Smith: Sp05: Rate: 3. Good graphics but poorly structured/organized. Make it more task oriented. http://www.phim.unibe.ch/comp_doc/c_manual/C/FUNCTIONS/funcref.htm http://www.macs.hw.ac.uk/~alison/alg/lectures/l2.pdf
B Smith: Add string compares, strcmp() Overview B Smith: Write up as SLOs • String Definitions and Pointer Arrays • Strings • Copying • Concatenation • Comparing B. Smith
array vs ptr notation array • The following two statements appear to be identical: • char test[5] = “abcd”; • and the statement: • char *test = "abcd"; • in that both will “declare” and initialize storage for the sequence • 'a', 'b', 'c','d','\0' B. Smith
String Copy Issues • Allowed: char *test = “abcdef”; test = “ghi"; test = "here is a longer string"; • Not allowed (WILL NOT COMPILE): char test[] = "abcdef"; test = “ghi"; The compile-time error : “incompatible types in assignment” • But! strcpy()canbe used, hence the following would be allowed: char test[] = "abcd"; strcpy(test, "efgh"); B. Smith
Arrays of Strings = Arrays of char* • The simple declaration char *myMovies[5];creates an array with 5 elements • each element is a pointer to a character (or string) • Use string assignments: myMovies[0] = “Blood Sport”; myMovies[1] = “The Hours”; myMovies[2] = “When Harry Met Sally"; myMovies[3] = "Jethro and The Hillbilly"; myMovies[4] = "The Pianist Plays the Organ"; char* movies[3]; movies[0]="blood sport"; movies[1]="kill bill"; movies[2]="the hours"; for(i=0;i<3;i++) puts(movies[i]); B. Smith
B Smith: Stopped here on 10/21/05 String Arrays • Each array element contains a starting address of a string • The initialization could be also be done in the array definition: char *myMovies[5] = {"Blood Sport", "The Hours", "When Harry Met Sally", "Jethro and The Hillbilly", "The Pianist Plays the Organ"}; B. Smith
N e m o \0 w a s a \0 f i s h \0 B Smith: Ask here or next slide the meaning of a[0][3] An Array of Pointers (addresses) B Smith: stopped here on 3/27/06 puzzler char *myWords[3] = {“Nemo”, “was a”, “fish”}; myWords[0] myWords[1] myWords[2] B. Smith
Formatting Strings w/printf() • Format specifiers work for strings also: printf("|%25s|", "My name is Frederick"); • is displayed as: Counting letters and spaces ( ), room for 25 characters |MynameisFrederick| Spaces are represented by B. Smith
Formatting Strings - example int main() { char message[81]; /* enough storage for a complete line */ char msg2[81] = "Thomas"; char *name = “Ann"; char *food = "Hamburgers and fries"; /*******************************************************/ printf("%s %s \n %s %s", “My name is ",msg2, “and I like ”, food); getchar(); /*******************************************************/ return 0; } B. Smith
The C String Library • The C string library is accessed by including string.h : #include <string.h> • The string library provides a number of useful functions for handling strings. • strlen – get the length of a string • strcpy – copy one string into another • strcat – add one string onto the end of another • strcmp – compare two strings for equality B. Smith
strlen and the length of strings • The length of a string is not equal to the length of the character array that contains it. • The length of a string is the number of characters before the ‘\0’ • The character array holding a string must be larger than the string (by one), but can be much larger. char state[50]; int length; strcpy(state,”Texas”); length = strlen(state); // length = 5 B. Smith
strcat: Concatenating Strings • strcat takes a character array as its first argument and either a character array or string literal as its second argument. #include <string.h> #include <stdio.h> int main() { char name[20]; strcpy(name,”James “); // name = “James “, length=6 strcat(name,”Knight”); // name = “James Knight”, length=12 strcat(name,”too many!!!”); // RUNTIME ERROR: Who knows when? strcat(“Nate”,”Knight”); // RUNTIME ERROR: SEGFAULT } B. Smith
strcmp: Comparing Strings • strcmp returns 0 if two strings are equal and otherwise returns a non-zero answer • Be careful to remember the reverse meaning: 0 means equal if(strcmp(string1, string2) == 0) printf(“The strings are equal.\n”); else printf(“The strings are not equal.\n”); // this is incorrect if( strcmp(string1, string2) ) printf(“The strings are equal.\n”); else printf(“The strings are not equal.\n”); B. Smith
String Use Tips • Always make sure the character array is long enough to hold the string and the ‘\0’ • Remember the meaning of strcmp results • Don’t confuse strcpy and strcat • Don’t try to cat or cpy a string into a string literal B. Smith
Reading Other Input with fgets • There are problems with using scanf to read numbers from the keyboard. • Using fgets to read input as a string is often a better approach. But how do we convert the string to a number? • The function sscanf (notice the extra s) acts like scanf, but on strings rather than standard input. B. Smith
Reading Strings from a User • The fgets function reads a string from a stream fgets(name, length, stdin) • name – the name of the character array • length – the maximum number of characters to read (plus one for the ‘\0’) • stdin – indicates to read from standard input • The reading of the string is terminated when a ‘\n’ is encountered. • The ‘\n’ is included in the string B. Smith
Example #include <stdio.h> #include <string.h> int main() { char firstName[100], lastName[100], char name[200]; // read the first name printf(“Enter your first name: “); fgets(firstName, sizeof(firstName), stdin); // read the last name printf(“Enter your last name: “); fgets(lastName, sizeof(lastName), stdin); // make name string strcpy(name,firstName); strcat(name, “ “); strcat(name,lastName); // print the name out to the screen printf(“The name is : %s\n”, name); return(0); } B. Smith
Example Continued Enter your first name: James Enter your last name: Knight The name is : James Knight • Something is not quite right. We need to remove the ‘\n’ from the end of the strings. • We need to add the lines // Chop the last character ‘\n’ off the strings firstName[strlen(firstName)-1] = ‘\0’; lastName[strlen(lastName)-1] = ‘\0’ B. Smith
In-Memory String Conversions scanf() vs sscanf() • sscanf() can be used for string disassembly • Assume the string "$199.23 44" is stored in the character array data • sscanf(data,"%c%lf %d", &dol, &price, &units); • This scans the string in data and strips out three data items • the dollar sign is stored in dol • 199.23 is converted to a double precision • 44 is stored in the variable units B Smith: Student asked for better motivation. When/why use this versus multiple scanfs? Answer: In our project, the data must be entered by the user all in one line. Multiple scanf’s would required an enter to be depressed each time. Also, this is very useful for string parsing! See project requirements. Also discuss how %*d will read in an integer, but not reassign it. B. Smith
sscanf example // Example of reading numbers with gets and sscanf #include <stdio.h> int main() { char line[400]; float height, weight; // read two numbers from a user on one line printf(“Enter your height and weight: “); fgets(line, sizeof(line),stdin ); // read the two numbers from the string to two floats sscanf(line, ”%f %f”, &height, &weight); return(0); } • The format for sscanf is sscanf( string, format string, variables ) B. Smith
B Smith: More examples!?! In-Memory String Conversions printf() vs sprintf() • printf("%d %d", mynum1, mynum2) is used to print data to the terminal (the standard output) • sprintf(destStrng,"%d %d", mynum1, mynum2) is used to redirect the output from the standard output to the string variable, destStrng • sprintf() is useful for string assembly . B. Smith
Review • Take care in copying strings. The following will work if test has been declared as a char *. • test = “ghi"; • An array of character pointers can be used for processing strings • The format specifier %s can be used for formatting an output string, e.g., • printf("|%-25s|", "My name is Frederick"); • sscanf() for string disassembly • sprintf() for string assembly B. Smith
Extra Slides B. Smith
N e m o \0 W a s a \0 F i s h \0 myWords[2][] myWords[0][] myWords[1][] myWords[0][] myWords[2][] myWords[1][] Pointer Arrays - Uses and Advantages B Smith: Don’t bring up strcmp without a proper introduction! • Two lines can be easily compared • pass their pointers to strcmp() • Two out-of-order lines can be easily exchanged • the pointers are exchanged (not the text lines) • Moving pointers is faster than moving blocks of text around B Smith: Is this slide correct? Is the order correct? Array Strings in “phone book” order if pointers are manipulated B. Smith