Professional Documents
Culture Documents
4002-208 Prog. With Classes (In C++)
4002-208 Prog. With Classes (In C++)
Objectives
Student should be able to use methods in the string class to: Find characters in a string. Break apart a string into smaller strings. Create large strings from smaller strings.
4002-208
Background
The pre-defined class string has attributes and methods. Main attribute is the characters of the string which are numbered starting with 0. Programs must include header file <string> Can be treated as almost a primitive type such as int, double, etc.
4002-208 3
length Method
Purpose: method length gives the number of characters. Method size does the same. Parameters: none Returns: length as integer Notes
An empty string has length of 0. A string with length n has characters in positions 0..n-1.
4002-208 4
Operator+
Adding together or concatenating strings Form: lhs + rhs Returns a string object whose contents are the combination of the content of lhs followed by those of rhs. Program: concat.cpp
4002-208
at Method
Purpose: method at extracts one character from a string at the specified position between 0 and length( )1 Parameter:
Position in string to be extracted.
find Method
Purpose: method find finds first occurrence of a single character in a string Parameter: 1 parameter of type char
Character to be found in string
Returns: position of character in the string or -1 if not found Note: search begins at start of string Program: find.cpp
4002-208 7
find Method
Purpose: method find finds first occurrence of a string in another string Two formats based on parameter type Parameters: 1 parameter of type string
String to be found in string
Returns: position of first character in the string or -1 if not found Note: search begins at start of string
4002-208 8
substr Method
Purpose: method substr returns a new string object created by copying parts of an existing string object. Two formats 1 or 2 parameters Parameters: (2 parameter format)
Starting position Number of characters
Returns: a new string with specified sub-string from starting position to the end of the string.
4002-208
10
Relational Operators
The standard relational operators can be used to compare two strings: <, <= >, >= ==, !=
4002-208
11
Sample Problem
Read a name with a space between first and last name. Find first space on a line Print first name Print last name Print name in form last,^first where ^ indicates one space.
4002-208 12