Docsity

Lecture 34: Strings in C - Dynamic Allocation and String Library, Study notes of Computer Science

Toggle sidebar
bg1
String
CGS 3460, Lecture 34
Apr 5, 2006
Hen-I Yang
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Lecture 34: Strings in C - Dynamic Allocation and String Library and more Study notes Computer Science in PDF only on Docsity!

StringCGS 3460, Lecture 34Apr 5, 2006Hen-I Yang

Previously… „^ Dynamic Allocated Arrays „^ Dynamic Allocated Strings „^ Strings

Strings „^ String: an array of characters „^ String constant (String literals) „^ String variable

String Literals „^ A string that has fixed constant value, e.g. “GoGators!” „^ \ or separate double quotation “” “” can be usedto split string literals into multiple lines „^ Null character ‘\0’ at the end of each string „^ Don’t get confused between string literal “a” andcharacter constant ‘a’. „^ Behind the scene:^ printf(“abc”);^

is handled as char * literal = “abc”;printf(literal);

String variables (II) „^ Initialization^ char^ location[20]^ =

“Gainesville^ Airport”;char location[20] = {‘G’,’a’,’i’,’n’,’e’,’s’,’v’,’,i’,’l’,’l’,’e’,’ ‘,’A’,’i’,’r’,’p’,’o’,’r’,’t’,’\0’}; „^ Like any other arrays, if length of the variable is less than 20,we’ll fill them up with \0 „^ Initialization string cannot be longer than the size of the stringdeclared „^ if you declare^ char^ location[]

=^ “Gainesville Airport”;^ and not specify its size, can you change the sizelater? No „ we can also declare^ char^ *****

location;^ array and pointers are closely related, but are not always interchangeable (e.g.location cannot point to somewhere else in array version) „ Always allocate memory before you use the dynamic pointerversion

Reading of Strings char^ str[]^ =^ “Clock

strikes^ 12”; printf(“The^ message:

%s\n”,^ str); „^ we can put the length in the conversionspecifications „^ Another way:^ puts(str);^ ^ no conversion specifications,^ ^ always ends with new line

String Library „ What is a library? „ #include <string.h> char * strcpy (char *s1, const char *s2);^

^ char * str1 = “abcd”;^ ^ char * str2 = (char *) malloc (5);strcpy(str2, “abcd”); char * strcat(char *s1, const char *s2);^ ^ strcpy(str1, “efg”); char * strcmp(const char * s1, const char * s2);^ ^ How to they compare? size_t strlen(const char * s)

String idioms „^ [Self-Study] „^ Counting the length of a string (observehow the code can be made compact) „^ Attach a string at the end of another string

By Popular Demand „^ Sample Code „^ Sample Code for Strings

Summary „^ Strings