11 - Strings - Engineering 101 Quote of the Day Success is...

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: Engineering 101 Quote of the Day Success is a lousy teacher. It seduces smart people into thinking they can't lose. - Bill Gates Strings Data Types and Classes Data Types Definition a set of possible values plus, plus, a set of legal operations on those values Members and Methods When we define a data item of a class type ifstream infile("input.dat"); infile("input.dat"); The result is to create a new member of that class By virtue of being a member, this object can be operated on by the methods of this class methods open close fail eof operator>> ... for example (int): (int): Integers within a given range Operations: addition (+), subtraction (-), etc. (+ (- C++ class mechanism: A general way to define new data types Example classes: istream, ofstream, string, ... Object-oriented programming : an approach emphasizing design and use of classes of data objects In this course we use classes, but will not define our own ifstream input.dat infile Declaring and Defining Data Objects General form: T identifier(arg_list); identifier(arg_list); Where: T is the type (class name) identifier is an identifier arg_list is a comma-separated list of zero or more commaarguments (depending on T) Invoking Methods To call a method for class member X: x.method(arg_list) method(arg_list) Where: . is the member selection operator method is the name of a method (member function) (member function) arg_list is a comma-separated list of zero or more arguments comma(depending on method) Examples: ifstream infile("input.dat"); infile("input.dat"); int i(0); Same as: int i = 0 Examples: infile.open("myinput.txt") infile.open("myinput.txt") infile.close() infile.close() cin.fail() cin.fail() 1 The String Class So far we have considered problems where the data we are manipulating is primarily numbers. Often the data we want to work with is not number, but rather text. text. The String Class The string class provides a way of manipulating text objects. To use the string class you must include it by putting an include line at the top of your C++ program: #include <string> Declaring a String To declare a string: string firstname; To assign a value to a string string firstname("Peter"); or string firstname = "Peter"; String literals are in "double-quotes" "double- Assigning a String You could do the same thing in two steps: string firstname; firstname = "Peter"; Adding Strings You can add strings together string firstname("Peter"); string lastname("Parker"); string fullname, occupation; fullname = firstname + " " + lastname; occupation = "superhero"; String Output You can send strings to files and standard output using << cout << "Name : " << fullname << endl; cout << "Job: " << occupation << endl; 2 Comparing Strings s < s2 Evaluates alphabetic order s > s2 s == s2 s <= s2 s >= s2 Note, however, that upper and lowercase letters are considered different. Uppercase letters come before lowercase letters alphabetically. Spaces and other characters are counted also. Line Input void getline(istream & in, string & line) Reads a whole line from an input stream, stores in a string Useful for extracting input with whitespace Operation >> getline Leading whitespace skipped included Termination condition any whitespace char newline ('\n') Consumes terminating character? no yes Data Abstraction So far, we have introduced ways to make strings (from literals) and manipulate them, without saying anything about how they are internally represented Principle of data abstraction: we can think abstraction: about algorithms operating on data without consideration of encoding and operation implementation details A class interface constitutes an abstract data type Strings as Compound Data Objects Compound data object: object: composed of more primitive data objects Strings are compound data objects, because they are composed of sequences of chars. In fact, the internal representation of a string is essentially this: "Michigan" 'M' 'i' 'c' 'h' 'i' 'g' 'a' 'n' Arrays Compound data objects: Comprised of a (potentially large) number of data items (elements) of the same type elements) Maintained in a sequence Supports reference by index (number in sequence) The Nature of Strings Strings are really lists of chars. The offset is an integer that tells how far from the front of the string a particular character lies. Strings support array semantics. semantics. This means you can reference any character by typing: identifier[offset] Array Index: Allows for random access Starts at zero (first element) Subsequent elements defined by offset from first element Reference an element of the array using the indexing operator : : array_name[index] array_name[index] identifier of array type integer expression 3 Referencing Characters For example: 0 1 2 3 4 567 Determine what it prints 1 A statement about man's fallibility 2 A statement about voting rights 3 A statement about historical fashion 4 A statement about Italian travel string s = "New_York" cout << s[0] << s[4] << endl; char char NY Determine what it prints 1 A statement about man's fallibility 2 A statement about voting rights 3 A statement about historical fashion 4 A statement about Italian travel Referencing Warning C++ allows you to reference outside the range!! string s("Michigan"); cout << s[-1] << s[10]<<endl; s[This will produce some unpredictable results! Referencing Warning Worse still you can assign to undefined reference locations string s("Michigan"); s[-1] = `x'; s[s[10] = `Y'; This will write into memory. Unused memory? Other variables used in this program? The execution code of your program? The execution code of your editor? Referencing Warning Consequences: Unanticipated results when data is changed in an unaddressed identifier. Program crashes: "Segmentation Fault" "General protection fault" Computer crashes (rare). 4 Referencing Warning Why? s[0] Referencing Warning Why? s[1] memory memory M i c h i g a n M i c h i g a n Referencing Warning Why? s[5] Referencing Warning Why? s[10] memory memory M i c h i g a n M i c h i g a n We don't know what could be in this memory location. It could be anything. It could be used by the program or another program. Strings: at( ) We can use the safer version of addressing, the at method string t("Silence"); t.at( 2 ) = t.at( 1 ); t.at( 1 ) = `c'; cout << t << endl; The at( ) method checks to see that you don't address beyond the length of the string. It does not always check for negative addresses. Other String Methods s.size( ) s.append(s2) s.push_back(c) s.find(s2) Number of chars in the string Appends s2 to s Appends char c to s Search for s2 in s and returns the location of the first character of the first match starting with zero or s.npos if not found string s("alex"); cout << s.find("ex"); // outputs 2 if(s.find("la") == s.npos){ cout << "didn't find la in " << s << endl; } 5 More Methods s.insert(offset, s2) s.erase(offset, num) s.replace(offset, num, s2) s.substr(offset, len) Insert s2 in s starting at offset erase num chars from s erase plus insert returns a new string that is the part of s that starts at offset and is len long Write a Program That Instills Positivity Read in a file line by line until the end of the file. Determine if the line contains the words "have to" "have to" If so, replace them with the words "want to" "want to" Print the line to standard output. I have to do my laundry I have to do my project I have to learn C++ I have to study tonight getline (istream&, string&) istream.fail( ) string.find(string2) == string.npos string.replace(offset, num, string2) I want to do my laundry I want to do my project I want to learn C++ I want to study tonight get a line istream failed didn't find string2 replace part of string by string2 string mystring("Michigan"); cout << mystring.substr(1,4); ichi Example: Which Program Works? 1: 2: Strings and C-strings CIt is important to note that the string class is a more modern version of a more basic type called the C-string. string. The literals we have used (e.g. "hello") are really C-strings. strings. Sometimes functions expect C-strings Cs.c_str( s.c_str( ) will return the C-string equivalent of the string s 3: 4: Strings and C-strings COne place this is required is when specifying file names for opening fstreams string filename; cout << "Enter Filename:"<< endl; getline(cin, filename); ifstream in(filename.c_str( ) ); Passing Strings to Functions and Procedures Generally we pass by value if we don't want to change the variable and by reference if we do pass-by-value int function( int x, int y); a copy is made for use in the function void procedure ( int & x, int & y); pass-by-reference access is given to the original data With strings we sometimes want to avoid recopying the string. It takes memory and time. 6 Passing Strings to Functions and Procedures To overcome this we can pass as a constant reference rather than by value int function( const string & x, const string &y); constant pass-by-reference read-only access is given to the original data Next Lecture Vectors and Vectors of Vectors void procedure ( string & x, string & y); pass-by-reference full access is given to the original data 7 ...
View Full Document

Ask a homework question - tutors are online