CIS 250 - strings
Objectives
- create and use C++ string objects
string class basics
- first include the appropriate library: #include <string>
- include the proper "using" statement: using std::string;
- declaring a string variable: string name;
- setting a string variable: name = "Kishwaukee College";
- declaring and initializing in one step: string name = "Kishwaukee College";
- string concatenation: str3 = str1 + str2;
- WARNING: string concatenation requires that at least one of the operands is a string object
- concatenation also works with characters: string fullName = firstName + ' ' + lastName;
- the array subscript operator works with string objects: cout << str1[5];
string class methods
- returns character at specified index: str1.at(index)
- returns character at specified index: str1[index]
- appends specified string to end of str1: str1.append(str2)
- appends n copies of character c to end of str1: str1.append(n , c)
- deletes all characters in str1: str1.clear()
- deletes all characters in str1: str1.erase()
- deletes n characters from str1 starting at index ndx: str1.erase(ndx, n)
- returns true iff str1 is empty: str1.empty()
- returns an integer value comparing str1 with str2: str1.compare(str2)
- less than 0 if str1 is less than str2
- greater than 0 if str1 is greater than str2
- equal to 0 if str1 is equal to str2
- Note: the string being passed in can be a const char* type
- Note: the position to start comparing can be specified for both strings
- Note: the lengths to be compared can be specified
- matching
- returns index of first match of str2 within str1: str1.find(str2)
- returns index of first match of str2 within str1 starting at index ndx within str1: str1.find(str2, ndx)
- returns index of first match of any character in str2 within str1: str1.find_first_of(str2)
- returns index of first match of any character in str2 within str1 starting at index ndx: str1.find_first_of(str2, ndx)
- returns index of first non-match of any character in str2 within str1: str1.find_first_not_of(str2)
- Note: other variations of this function search for a substring of a specified length
- inserts str2 starting at position ndx in str1: str1.insert(ndx, str2)
- inserts n copies of character c starting at position ndx in str1: str1.insert(ndx, n, c)
- returns the length of str1: str1.length()
- returns the length of str1: str1.size()
- replaces n characters in str1 starting at position ndx with all the characters in str2: str1.replace(ndx, n, str2)
- returns the substring of str1 starting at ndx which is length characters long: str1.substr(ndx, length)
- swaps the contents of str1 and str2: str1.swap(str2)