120 likes | 222 Views
Principles of Computer Science I Honors Section. Note Set 9 CSE 1341. Today. STL String. string objects. sequence of characters much like a null-terminated c-string Pro’s easier to program with don’t have to worry about array length don’t have to deal with pointers Con’s
E N D
Principles of Computer Science IHonors Section Note Set 9 CSE 1341
Today STL String
string objects • sequence of characters much like a null-terminated c-string • Pro’s • easier to program with • don’t have to worry about array length • don’t have to deal with pointers • Con’s • Heavyweight library (pre-programmed “stuff”) • Not practical for all software deployment environments
Declaring a String Object #include <string> //new header file to use strings int main() { string s; string t = “CSE1341H”; string u (“CSE1341H”); }
String Usage string dept = “CSE”; string course = “1341H”; string cls = dept + course; cout << cls; cls += “ is awesome!”; cout << cls;
String Usage string fname; string lname; cout << “Enter first name: “; cin >> fname; cout << “Enter last name: “; cin >> lname; cout << lname << “, “ << fname;
String Usage string fname; string lname; cout << “Enter first name: “; cin >> fname; cout << “Enter last name: “; cin >> lname; cout << lname << “, “ << fname;
String Usage string sent; cout << "Enter something with spaces: "; getline(cin, sent); //Different cout << sent;
String Object Member Functions • C++ objects put together in nice, neat little packages • some data • some functions to operate on that data • Remember cin.getline(…)?? • cin was an object that knew about getting “stuff” from the keyboard • getline was a function that you could use to ask cin to get some information from the keyboard
String Object Member Functions • Strings are objects whose data is a sequence of characters. • You can ask a string • its size() – Number of characters in the string • its capacity() – Number of characters it can hold before it needs to resize (behind the scenes).