Jan 14, 2002 Reading assignment: Deitel and Deitel pp. 343-345, and sections 19.1 - 19.9 -or Wang pp 37-39, 63-65 and 222-225 Character arrays and C-style string: - There's a special way to define and initialize character arrays: char str[] = "This is a string"; These are called c-style strings and are null terminated, so 11 slots 11 slots are reserved for this array; - There are special functions in the string handling library for dealing with c-style strings, such as strlen, or strcmp, etc. See page 345 in Deitel and Deitel - There is another way to store strings - with the string class from the standard library. This is a more robust system that I recommend you favor over C-style strings. Strings: - Use #include <string> to get the string class header file - Define a string with a variety of initializers string str1("This is a string"); string str2 = "This is another string"; string str3(8,'x'); /* string of 8 'x' characters */ string str4("String part 1" " and part2 are concatentated together"); and *not* string no_good('x'); - string objects may not be null-terminated - Individual characters can be accessed with str1[5], for example, indexed started at 0. Alternately, you can use str1.at(5) - >> works with strings, as in cin >> str3; - Unlike arrays, you can assign strings, as in str1 = str2; or str1.assign(str2); - You can add strings, as in str3 = str1 + str2; str1 and str2 are concatenated and copied into str3 - You can append onto strings, as in str1.append(", ya betcha!); - Strings can be compared, as in if (str1 == str2) or if (str1 <= str2) or int f = str1.compare(str2) (f = 0 if equal, f is negative if str1 is lexicographically less than str2, f positive otherwise) or int f = str1.compare(2, 5, str2, 0, 5) which compares 5 characters of str1 starting with subscript 2 with 5 characters of str2 starting with subscript 0. - str1.length returns the length of the string - If you perform an operation that changes the length of the string, the string class allocates (or releases) memory and updates the string length - You can get a substring of a string, for example str2 = str1.substr(2, 3) gives a substring 3 characters long starting at index 2 - str1.empty returns true if there are no characters in the string - Know that there are several search routines, such as str1.find("search string"); which returns the subscript of the first found location or string::npos if not found. str1.rfind searches from the end of the string, and there are a few others as well - Know that there are several replacement and insertion routines: str1.erase, str1.replace, str1.insertPrograms from class today:
Character array style: repeats.cpp
String style: repeats_alt.cpp