CS110_05b_arrays4strings

CS110_05b_arrays4strings - Arrays For Strings Jack Tumblin

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Arrays For Strings Jack Tumblin jet@cs.northwestern.edu EECS110: 5b I hope you: Have passed some arrays to functions, and Used those arrays as both fcn. input and output 1 (Recall) Arrays and Functions void cleanArray2(int siz, int a); //fcn prototype ... int main(void) { int count[5] = {5,4,3,2,1}; cleanArray2(5, count); printArray (5, count); return 0; } void cleanArray2{int siz, int a) // fcn body: { // clear 1st `siz' elements int i; for (i=0; i<siz; i++) a[i]=0; } 2 // use array name (Recall) Arrays and Functions void cleanArray(int siz, int a); // prototype ... int main(void) { int count[5] = {5,4,3,2,1}; cleanArray2(5, count); printArray(5, count); return 0; } Array name count gives array's 0th byte location, function `cleanArray2() copies that address to define its own local array named a , so that a array starts at same memory location as count! 3 (Recall) Arrays and Memory a ... 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 ... count count[0] count[1] While cleanArray2() runs, its a array uses the same memory locations use by the count array. Any changes to a array are changes to count. Address Address count[2] count[3] 4 Strings: The 3rd Big Idea Text Computing > Math Computing (for most of us; for a very few, Text >= Math) NOW we're ready for it! we have interfaces/libraries, arrays / indexing / memory addresses It soon leads to a 4th Big Idea : pointers Chapter 9 is a bit dry: we'll try another story... 5 Strings: The 3rd Big Idea CS Jargon: a `string' is an abstract data type Jargon An generalized assemblage of other data types (char), `A single piece of text' made of a set of char values, Any desired length, any desired order Any desired characters (except one), Format Specifier (for printf,scanf, etc): %s String Examples: a;sldk#%2 2@ 2 $ $#_+VA12*$ 78 " The night has %d eyes\n " ?THIS is not my beautiful life! >TalkingHeads: 6 | SOMETHING IS MISSING! Character literals: 'a' 'R' '9' '\n' '\t' double quotes single quotes Character variables: char ans = 'y'; String literals: "average value is %f\n" "%d of your base are belong to us" "hit any key to continue" ?String Variables? How? Variables 7 Strings in Memory ... 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 ... `h' `e' `l' `l' `o' ` ' `w' `o' `r' `l' `d' `!' NULL in the C language, A `string' is a list of char values, stored sequentially in memory, always ended by a `NULL' char value. Address Address 8 Strings in Memory ?!?! NULL ?!?! an unprintable `special' character (see Appendix A) Why? NULL is a sentinel: it means `end of the string!' sentinel How? in C, NULL character constant is also '\0' What? the stored numerical value for NULL is zero: char ch[2]; ch[0] = '\0'; // set both to NULL ch[1] = NULL; // (same as `\0' character printf("NULL is %d,%d",(int)ch[0],(int)ch[1]); produces > NULL is 0,0 (cast it from char to integer) 9 String Variables (Recall) A variable is: a place-holder, a named chunk of memory to hold just one value that can change A string is: a sequential list of char values, that ends at NULL (`\0'). Thus: an array of type char is one way to make a `string variable' (but array size is fixed; the string must fit inside!!) Let's try it: 10 Put String in a char Array : I ... 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 ... msg `h' `e' `l' `l' `o' ` ' `w' `o' `r' `l' `d' `!' `\0' int main() { char msg[20]; uses char literals; fill the char array with char constants Address Address msg[0] = `h'; msg[1] = `e'; msg[2] = `l'; msg[3] = `l'; msg[4] = `o'; msg[5] = `\0'; ... /* WHY is this so tedious?!? */ printf("%s\n",msg); } result: > hello 11 Put String in a char Array : II ... 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 ... msg `h' `e' `l' `l' `o' ` ' `w' `o' `r' `l' `d' `!' `\0' int main() { char msg[20]={'h','e','l','l','o',' ', 'w','o','r','l','d','\0'}; printf("%s",msg); /* not much better... */ } Address Address result: > hello world uses char literals; fill the char array with char constants 12 Put String in a char Array : III ... 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 ... msg `h' `e' `l' `l' `o' ` ' `w' `o' `r' `l' `d' `!' `\0' int main() { char msg[20]={"hello world!"}; printf("%s",msg); /* AH! that's the way!... */ } Address Address result: > hello world! uses a string literal; double-quotes make a `string constant' 13 Strings in Arrays A char array is a fairly good `string variable', and you can initialize it with a string constant: char msg[80]= {"one line of text."}; 14 Strings in Arrays A char array is a fairly good `string variable', and you can initialize it with a string constant: char msg[80]= {"one line of text."}; Print a string variable using %s and printf(); printf("You typed %s", msg); 15 Strings in Arrays A char array is a fairly good `string variable', and you can initialize it with a string constant: char msg[80]= {"one line of text."}; Print a string variable using %s and printf(); printf("You typed %s", msg); Read a string variable using %s and scanf(); printf("Type answer, press return:"); scanf(" %s", msg); 16 Strings in Arrays SURPRISE! A char array is a fairly good `string variable', scanf() can NO ampersand (& for string variables and you uses initialize it with) a string constant: (array name), unlike ordinary variables WHY? char msg[80]= {"one line of text."}; --array name is an address--of the 0th array element --for ordinary variable `var', Print a string variable using %s and address of var' writing `&var' means `give me the printf(); printf("You typed %s", msg); Read a string variable using %s and scanf(); printf("Type answer, press return:"); scanf(" %s", msg); 17 Basic `String Variable' Actions How can I . . . Assign: copy a string from one array to another? Append: copy one string onto the end of another? Find: find a given character in a string? (find all `e') Parse: find the 1st,2nd,3rd... Nth word in a string? Match: find a given key word in a string? Delete: remove one character from a string? Erase: remove one word from a string? You know how!---with loops, if/else, = =, etc. 18 Strings in Arrays Problem: Many common tasks are tedious: copy a string constant to a string variable; append one string to the end of another; remove the first part or last part of a string . . . Solution: function library for tedious tasks #include <string.h> // see Appendix F.6 in book 19 Solution: #include <string.h> Use the `string.h' library to do the tedium: a vital part of C (see book's appendices for summary) #include <stdio.h> #include <string.h> int main() { char msg[20]; strcpy(msg,"Hello world!"); printf("my string:%s\n",msg); } Result: > my string:Hello world! > // for printf() // for strcpy() (Recall) String literal: . "text in quotes" %s means "a string" OK for scanf() too. 20 Solution: #include <string.h> Book neglects it, but string.h has everything you need: all chars Find string length Copy a string Join 2 strings Compare 2 strings (later:) Find a char in a string Find a string in a string strlen() first n chars strcpy() strncpy() strcat() strncat() strcmp() strncmp() strchr() strrchr() strstr() 21 String Length: int strlen(src) #include <stdio.h> #include <string.h> // for printf() // for strlen() int main() { char msg[20] = {"Hello world!"}; cnt = strlen(msg); printf("length of \"%s\" is: %d\n",cnt); } Result: 123456789_12 > length of "Hello world!" is: 12 > 22 String Copy: strcpy(dest, src) #include <stdio.h> #include <string.h> int main() { char msg[20]; strcpy(msg,"Hello world!"); printf("my string:%s\n",msg); } Result: > my string: Hello world! > 23 // for printf() // for strcpy() strcpy() is the string `assignment' operator String Copy: strncpy(dest,src,cnt) #include <stdio.h> #include <string.h> int main() { char msg[20]; // for printf() // for strncpy() Copy only 1st 3 chars char strncpy(msg,"Hello world!", 3); printf("my string:%s\n",msg); } Result: > my string: Hel > 24 String Merge: strcat(str1,str2) #include <stdio.h> #include <string.h> int main() { char msg1[81],msg2[81]; strcpy(msg1,"Hello you!"); strcpy(msg2,"Hello me!"); strcat(msg1,msg2); printf("%s\n", msg1); } Result: > Hello you!Hello me! > 25 // for printf() // for strcat() msg1 is BOTH input and output to strcat() fcn! String Merge: strncat(str1,str2,cnt) #include <stdio.h> #include <string.h> int main() { char msg1[81],msg2[81]; // for printf() // for strncat() Append only 1st 3 chars char msg1 is BOTH input and output to strcat() fcn! strcpy(msg1,"Hello you!"); strcpy(msg2,"Hello me!""); strncat(msg1,msg2,3); printf("%s\n", msg1); } Result: > Hello you!Hel > 26 String Compare: int strcmp(a,b) #include <stdio.h> #include <string.h> // for printf() // for strcmp() int main() { //123456789_123456789_ char msg1[81] = {"Hello to you!"}; char msg2[81] = {"Hello to me!"}; int diff; diff = strcmp(msg1,msg2); if(0==diff) printf("same!\n"); else printf("different!\n"); } Result: > different! > 27 String Compare: int strncmp(a,b,cnt) #include <stdio.h> #include <string.h> // for printf() // for strncmp() int main() { char msg1[81] = {"Hello to you!"}; char msg2[81] = {"Hello to me!"}; int diff; diff = strncmp(msg1,msg2,6); if(0==diff) printf("same!\n"); else printf("different!\n"); } Result: > same! > compare only the 1st 6 chars char 28 ...
View Full Document

This note was uploaded on 10/05/2011 for the course COMPUTER S 110-1 taught by Professor Tumblin during the Spring '11 term at Northwestern.

Ask a homework question - tutors are online