1 / 34

The C++ String Class

The C++ String Class The contents of this particular lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh. The C++ String Class - Strings are defined in the Standard Class Library - while not part of the language, any standard

jaymiller
Télécharger la présentation

The C++ String Class

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The C++ String Class The contents of this particular lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh

  2. The C++ String Class - Strings are defined in the Standard Class Library - while not part of the language, any standard compiler will include this class in its library - This depends on the compiler - writers - you have to rely on the fact that they've properly implemented the same string operations that everybody else does - To obtain the String Class library use #include <string>

  3. The C++ String Class - To declare a variable of type string: #include <string> // declaring 3 variables of type string string play, author, mainCharacter; - We can assign to strings: play = “Hamlet”; author = “W. Shakespeare”; mainCharacter = play;// assign to string - Notice: we don’t worry about the length!

  4. String Class I/O - Do I/O on a string in a natural way: string name = “Jim Anderson”; cout << “My name is ” << name << endl; - The output is: My name is Jim Anderson <See: Example 1>

  5. String Class I/O - String class input: cin >> name;// reads first word from input stream cout << name; - Suppose user enter “Marky Ramone” program prints “Marky” (not “Marky Ramone”) - >> skips over whitespace characters, reads next word (until next whitespace character) - Notice the difference << print out the entire string >> read in the next (whitespace delimited) word

  6. String Class I/O - Often want to read the entire line of text (up to and including the newline character) - the string class has the getline function getline(cin, name); // read next line into name - if I type This is CS211 then string variable name will contain This is CS211

  7. String Class I/O - A simple program to copy one file to another #include <string> #include <fstream> int main() { string line; ifstream infile; ofstream outfile; infile.open("infile.txt"); outfile.open("outfile.txt"); getline(infile,line); while (!infile.eof()) { outfile << line << endl; // note: need endl getline(infile, line); } infile.close(); outfile.close(); } <See: Example 2>

  8. String Element Access - Access and modify individual characters of a string, much like an array of char: - Example: string line; line = "This is a line of text"; cout << line[5]; line[2]= 'u'; cout << line << endl; - Output: iThus is a line of text

  9. String Element Access - String bounds are checked: - access a string at an index beyond the last character (or <0) causes a run-time error - Where is the end of the string? - there is a size() function, which returns the current length of the string

  10. String Element Access - Example of "size" function: string name=“Adam Smith"; cout << name << " has " << name.size() << " characters in his name" << endl; - Output: Adam Smith has 10 characters in his name - Characters are stored at indices

  11. Strings: Dynamic Data - Strings are a dynamic data type in that the length can be different at different points in the program execution: string quote; quote = "I am a student at CSUSM."; cout << quote.size() << " "; quote = "I am a student."; cout << quote.size() << endl; - Output: 24 15

  12. Strings as Parameters - Strings behave "normally" when used as parameters - can be passed by value, or reference (with &) - unlike C-style strings, or arrays of chars for that matter, which are always passed by reference - can still use size() inside a function - the whole object gets passed, all members are accessible - can be returned from functions - unlike C-style strings which can't be easily returned from functions - Essentially, strings behave like ints when used as parameters/return values

  13. Strings as Value Parameters string reverse(string line) { int i; char tmp; for (i= 0; i< line.size()/2; i++) { tmp= line[i]; line[i]= line[line.size()-1-i]; line[line.size()-1-i] = tmp; } return line; }

  14. Strings as Value Parameters - Call this function as follows: string line1, line2; line1= “This is Adam Smith"; line2= reverse( line1); cout << line1 << endl; cout << line2 << endl; - The output is: This is Adam Smith htimS madA si sihT - Note: line1 does not change!

  15. Strings as Reference Parameters - Use a reference parameter void reverse2( string& line) { int i; char tmp; for (i= 0; i<line.size()/2; i++) { tmp= line[i]; line[i]= line[line.size()-1-i]; line[line.size()-1-i]= tmp; } } - line is now a reference parameter

  16. Strings as Reference Parameters - Try out reverse2: string line1, line2; line1="This is Mr. Brown"; cout << line1 << endl; reverse2(line1); cout << line1 << endl; - Output: This is Mr. Brown nworB .rM si sihT <See: Example 4>

  17. String Relational Operators - The string class provides many operators and functions which work with strings - Relational operators - strings can be compared much like integers using the operators ==, !=, <, <=, >, >= - the equality operator (==) and inequality operator (!=) work as you would expect.

  18. String Operators: Concatenation - Another operator provided by the string class library is concatenation using +: string word1, word2, word3, line="I "; word1="am "; word2=”an "; word3="instructor in this college" ; line= line+ word1 + word2 + word3; cout << line << " " << line.size() << endl; - Output: I am an instructor in this college 34 - Notice: the string line grew dynamically! <See Example 5>

  19. String Operators: Concatenation - This is an example of operator overloading - operator + is used for ints, floats, and strings - has a different meaning in each case - operator + for strings is actually not part of C++ - it is part of the C++ class library <string> - you can (in the future) define your own meanings for various operators

  20. "Shortcut" operators - C++ provides a series of shorthand operators for performing an operation with the same variable you intend to assign the result to - Instead of Try x= x+ y; x+= y; x= x* 2; x*= 2; - … and so on. - Feel free to use these!

  21. Overloading Shortcuts - The reason I bring this up is that += is overloaded for strings as well - you can write: line += word1+ word2+ word3; - same meaning as line = line+ word1+ word2+ word3; - The others don't make sense for strings, but you may see them overloaded for other types - and as already stated possible to overload them yourself

  22. String Member Functions - The string class provides a number of useful member functions - Object-Oriented-Programming (OOP) - recall that member functions of a class are functions which operate on objects of that class (really part of the object!) - sometimes called "Methods” - notation is: VariableName.FunctionName(...) - the function FunctionName operates on the object (string) VariableName - may have some other parameters as well (e.g. fin.open(…) for file streams)

  23. String Member Functions - Substrings: - the string class provides the substr member function to extract substrings from a string - Specification: string str1, str2; str2= str1.substr( first, numchars); - str2 is assigned the substring of str1 starting at position first and containing numchars characters - if str1 does not have numchars chars after first, str2 just copies up to end of str1

  24. String Member Functions - Substrings (continued) - Example: string line="This course is not that hard guys"; string line2, line3; line2 = line.substr(5,6); line3 = line.substr(15,8); cout << "line 2 is: \""<< line2 <<"\""<< endl; cout << "line 3 is: \"" << line3 << "\""<< endl; – Output: line 2 is: “course” line 3 is: “not that” <See Example 6>

  25. String Member Functions - Substring replacement - The substr function does not modify its object - If you want to change a substring, use the replace function - Specification: string str1, str2; str1.replace( first, numchars, str2); - Action: - replace chars in str1, starting at index first and extending numchars positions, with the string str2.

  26. String Member Functions - Example string line="Let us now replace some text."; line.replace( 4, 10, "it snow. P"); cout << line << endl; - Output Let it snow. Place some text. - Note that "it snow. P" contains 10 chars and we replaced 10 chars. This is not always necessary <See Example 7>

  27. String Member Functions - Can replace substrings with shorter or longer substrings - the length of the string will change - Example: string line="Let us now replace some text."; cout << line.size() << “ ” ; line.replace(4, 19, "it snow"); cout << line << “ ” << line.size() << endl; – Output: 30 Let it snow text. 18

  28. String Member Functions - Two other member functions closely related to replace are erase and insert. - these functions can be done with replace - more convenient and suggestive to use erase and insert when appropriate

  29. String Member Functions - Erase: - Specification: string line; line.erase( start, numchars); - delete numchars chars starting at index start - functionally same as: line.replace( start, numchars, ""); - "" is the null string (length 0)

  30. String Member Functions - Insert: - Specification: string line, instr; line.insert( start, instr); - insert string instr into line, starting at index start - don't overwrite any characters in line just shift to the right - functionally same as: line.replace( start, 0, instr); - replace 0 characters of line, starting at position start, with instr

  31. String Member Functions - Examples: string line="Walking on the sun is hot"; line.erase(15,4); cout << line << endl; line.insert(15,"moon "); cout << line << endl; - Output: Walking on the is hot Walking on the moon is hot <See Example 8>

  32. String Search Functions - The string class also offers a very useful searching function: find - Specification: string line, pattern; int pos, x; ... x = line.find( pattern, pos); - x will contain the first location of pattern within line starting at or after position pos or line.npos (a special constant) if pattern not found in line at or after position pos

  33. String Search Functions - Example: string line=" This and that and more and less"; int p; p= line.find( "and" ,0); // search, start at pos'n 0 while (p != line.npos) { cout << "Found an \" and\" at index " << p << endl; // continue looking at location p+ 1 p= line.find("and", p+1); } Output: Found an “and” at index 6 Found an “and” at index 15 Found an “and” at index 24 <See Example 9>

  34. Makes Sure to Study all the examples for this lecture. • Specially, examples 10 and 11 are very important. Similar questions may appear in the labs, assignments and exams

More Related