1 / 27

The Standard String Class

The Standard String Class. Is actually a template: typedef basic_string<char> string This means you can have strings of things other than chars. Accessing Elements. You can access the elements via the subscript operator std::string fred = "hello"; std::cout << fred[0];

marcos
Télécharger la présentation

The Standard 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 Standard String Class • Is actually a template: • typedef basic_string<char> string • This means you can have strings of things other than chars

  2. Accessing Elements • You can access the elements via the subscript operator std::string fred = "hello"; std::cout << fred[0]; • Or through the at method std::string fred = "hello"; std::cout << fred.at(0); • at() throws an out_of_range on bad access

  3. Constructors • C-style string, string, char sequence, and parts there-of • string s1; // default - empty string • string s2 = "hello"; // C-style string • string s3(5,'h'); // ”hhhhh” • string s4 = s3; //copy of s3 • string s5(s2,1,2); // ”el” • const char *cp = "hello"; • string s6(cp+1,2); //"el" again • string s7(cp,1,2); //func. resolution

  4. Assignment • Lot's of versions again • string s1 = "family"; • string s2 = "guy"; • s1 = s2; // assign a string • s1 = "fred"; // assign a C-style string • s2 = 'h'; // assign a char • There are also assign() methods for other constructor equivalents (since assignment operators can’t have multiple arguments)

  5. Comparisons • Operator overloading provides for string and c-style string compares • There are also compare methods which return ints ala strcmp • The simple <,<=,==,>=,>,!= usually suffice though

  6. Appending • += is overloaded for appending strings, c-style strings, and chars • There is also an append method: string& append(const string &str); string& append(const string &str, size_type pos, size_type n); string& append(const char *p, size_type n); string& append(const char *p); string& append(size_type n, char c);

  7. Insertion • Similar to appending, but a position is required • The characters are inserted before the position string& insert(size_type pos, const string &str); string& insert(size_type pos, const string &str, size_type pos1, size_type n); string& insert(size_type pos, char *p, size_type n); string& insert(size_type pos, char *p, size_type n); string& insert(size_type pos, size_type n, char c);

  8. Concatenation • Performed via an overloaded + operator • Works for strings • And C-style strings • And chars

  9. Searching • Can search for strings, C-style strings, and chars • Can find first or last occurance of the item • Or first or last occurance of any of the items elements • Or first or last occurance of any characters not in the item

  10. Searching std::string s = "accdcde"; s.find("cd"); //return 2 s.rfind("cd"); //returns 4 s.find_first_of("cd"); //returns 1 s.find_last_of("cd"); // returns 5 s.find_first_not_of("cd");//returns 0 s.find_last_not_of("cd"); //returns 6

  11. Replace • Replaces a substring with another string • Has as many forms as the constructors string& replace(size_type i, size_type n, const string &str); string& replace(size_type i, size_type n, const string &str, size_type i2, size_type n2); string& replace(size_type i, size_type n, const char *p, size_type n2); string& replace(size_type i, size_type n, const char *p); string& replace(size_type i, size_type n, size_type n2, char c);

  12. Substring • Returns a new string object representing the substring string substr(size_type i, size_type n) const • Combines well with find and replace

  13. Misc. Methods • length() and size() give the string length • max_size() gives the maximum size of a string • empty() returns true if the string is empty • erase(size_type i=0, size_type n=npos) empties the string • Notice that erase() can be done with replace()

  14. Converting to C-Style Strings • The c_str() method returns a const char* • The data() method is similar but does not add the '\0’ • The array returned is managed by the string • Calling a non-const method invalidates it

  15. Input/Output • strings can be output with operator<< • They can be input with operator>> in which case words are read • There is also a getline(istream&,string&) function • getline reads a line from input into the string • Input into strings is better than char arrays • Mainly because the string will expand as necessary

  16. The Standard Streams • Yet another template you have been using without knowing • typedef basic_ostream<char> ostream • Same reasons as string for being a template

  17. Output Streams • You should know how to use these by now • You should know how to overload << by now • Note that operator<< aren't members and thus aren't virtual • When dealing with inheritance it is common to: class Base { virtual ostream& put(ostream &os) const; }; ostream& operator<<(ostream& os, const Base &b) { return b.put(os); }

  18. Input Streams • Again you should have some experience with these by now • Virtual functions don't matter as much • But the same technique can be used • Should always test the result of a read and not just assume it worked

  19. Stream State • All istream and ostream’s have the following methods • bool good() const true if all has gone well • bool eof() const true if reached end of input • bool fail() const true if next operation will fail • bool bad() const true if stream may be corrupt

  20. Formatting • We can change the format that C++ uses to output values • The setf() and unsetf() methods are used • The flags we can use are defined in ios_base • cout.setf(ios_base::oct,ios_base::basefield) • ouput integers in octal • cout.setf(ios_base::scientific, ios_base::floatfield) • output floating point in scientific format

  21. Formatting II • Can also set field widths and fill characters width() and fill() are used • cout.width(4); • cout.fill('*'); • cout << "hi"; //will output '##hi' • We can use left, right, and internal in ios_base to change placement • Changes only apply to the next output operation

  22. Manipulators • Manipulators are a simpler way of manipulating streams • They are used in the standard << output notation • std::cout << 12 << ' ' << oct << 12 << endl; • std::cout << setw(4) << setfill('*') << "hi"; • You need to #include <iomanip>

  23. File Streams • Reading and writing from files is the same as using cin and cout • Except you have to open them first • ifstreams are for reading files • ofstreams are for writing files • fstreams are for additional options (read and write, append mode, etc)

  24. Strstreams • A string in memory can also be used as a stream • Our compiler and the standard disagree on this bit. • strstream has been replaced with stringstream (which acts on string obects insted of char*s) • Our compiler doesn’t support stringstreams.

  25. Input String Streams #include <iostream> #include <string> #include <strstream> void word(const char* s) { istrstream istr(s); string w; while (istr >> w) cout << w << endl; } int main() { word("here is a short string"); }

  26. Output String Streams #include <iostream> #include <strstream> #include <iomanip> int main() { char a[100] = ""; ostrstream out(a,100); out << setw(50) << setfill('*') << "a string" << endl; cout << a; }

  27. Closing Streams • The close() method closes a stream • Usually it is not needed as the destructor performs the close • Sometimes closing a file can be useful, though

More Related