Strings

Objective

  • 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)