STRINGS IN C FUNCTIONS DEALING WITH CHARACTERS FUNCTIONS DEALING WITH STRINGS
How to Declare a String? n n n n 1. Need to have a name for the string 2. Need to know the length of the string 3. Actual memory space needed is length of the string + 1 (to take care of the NULL character) 4. Data type is char Example: char Str[20];
Arrays of strings n n n It is also possible to have arrays of strings. Since strings are themselves arrays, then we need to add a second size. An array of strings is in fact an array with two dimensions, width (columns) and height (rows). char list_cities[100][15]; will be able to contain 100 city names with a maximum of 14 letters per city. Why not 15?
Arrays of strings (cont. ) n Example: An array containing the names of the months. n char months [12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”};
Arrays of strings (cont. ) Example: An array containing the names of the months. char months [12][10] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; Can you find the value of months[3]? How about months [7][3]?
Using Pointers for String Manipulation n n n n /* PROGRAM # 96 */ /* DEMONSTRATES DISPLAYING STRING USING POINTER*/ #include <stdio. h> #define ssize 6 main( ){ char *ptr, str[ ] = "BIRDS"; int i; ptr = str; printf("Our string is %s. n", str); n /*Display character string contains, using pointer */ puts(“Our string is made out of the following characters: ”); for(i=0; i<ssize; i++) printf("%c ", *(ptr+i)); n n n puts(“Our string is made out of the following characters: ”); for(i=0; i<ssize; i++) printf("%c ", str[i]); n n }
Memory Map – Usage of pointer vs. index of string Address memory Pointer Usage String element 2400 ‘B’ *(ptr+0) Str[0] 2401 ‘I’ *(ptr+1) Str[1] 2402 ‘R’ *(ptr+2) Str[2] 2403 ‘D’ *(ptr+3) Str[3] 2404 ‘S’ *(ptr+4) Str[4] 2405 ‘ ’ *(ptr+5) Str[5]