# Section 10: String

## Class String

1. You need to include string library to use string. Also, you can use getline to get the string from the user input.
2. You can use cin to get the string directly and it won’t get the line break. For example, output1 typed “Hi” and then enter to type “World”, it will show two separate strings respectively. Also, output 2 types “Hello World”, it will print Hello World separately. Not like char, you need to use cin.ignore() to ignore the line break.

## Basic Functions of Class String

1. Basic functions of class string.
• s.length()
• s.size()
• s.capacity()
• s.resize(30)
• s.max_size()
• s.clear()
• s.empty()
2. Example

## Class String - Append and Insert Functions

1. Append and insert functions
• s.append(“Bye”)
• s.insert(3, “kk”)
• s.replace(3, 5, “aa”)
• s.erase()
• s.push_back(‘z’)
• s.pop_back()
• s1.swap(s2)
2. append() example.
3. insert() example, the third parameters is word number you like to insert.
4. replace() example, the first parameter is the position start to replace and the second parameters is how many characters you want to replace with.
5. push_back() example, the parameter can only be char type.
6. pop_back() example, it removes the last character.
7. swap() example.

## String Class - Copy and Find Functions

1. Copy and Find Functions.
• s.copy(char desp[])
• s.find(str) or char
• s.rfind(str)
• s.find_first_of()
• s.find_last_of()
• s.substr(start, number)
• s.compare(str)
2. copy() example.
3. In default, find() finds the words from the left. rfind() finds the words from the right. If the words can’t be found, it will return large number.
4. find_first_of() and find_last_of() examples. The second parameter is the position that you want to start your search. You can also put more than one letter as the first parameter, it will find one of the letter and return the position. find_last_of() will find from the back and return the last position of your parameter.
5. substr() example. The second parameter is the length of return string.
6. compare() example.
7. Example of string operator.

## String Class - Iterator

1. Iterator
• string::iterator
• begin()
• end()
• reverse_iterator
• rbegin()
• rend()
2. String iterator example.

## Find Length of a String

1. There are two ways to find the length of a string, use str[i] != '\0' or iterator.

## Practice Problem: Change Cases of Letters

1. Change to lowercase example.
2. Change to uppercase example.

1. Example.

1. Example.