1 / 85

Class string and String Stream Processing

18. Class string and String Stream Processing. OBJECTIVES. In this chapter you will learn: To create and use struct s. To pass struct s to functions by value and by reference.

zenia
Download Presentation

Class string and String Stream Processing

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 18 • Class string andString StreamProcessing

  2. OBJECTIVES In this chapter you will learn: • To create and use structs. • To pass structs to functions by value and by reference. • To use typedef to create aliases for previously defined data types and structs. To use class string from the C++ Standard Library to treat strings as full-fledged objects. • To assign, concatenate, compare, search and swap strings. • To determine string characteristics. • To find, replace and insert characters in a string. • To convert strings to C-style strings and vice versa. • To use string iterators. • To perform input from and output to strings in memory.

  3. Introduction • Structures • Similar to classes • Can contain access specifiers, member functions, constructors and destructors • Only difference is that structure members are public by default (class members are private by default) • Bitfields • Can specify the exact number of bits to use for a variable • C-style string manipulation functions • Process blocks of memory as arrays of bytes

  4. Structure Definitions • Structures • Aggregate data types • Built using elements of several types

  5. Structure Definitions (Cont.) • Structures (Cont.) • Example • struct Card{ char *face; char *suit;}; • Keyword struct • Structure name Card • Used to declare variables of the structure type • Data members face and suit • Must have unique names • Ending semicolon

  6. Common Programming Error • Forgetting the semicolon that terminates a structure definition is a syntax error.

  7. Structure Definitions (Cont.) • Structures (Cont.) • Structure cannot contain an instance of itself • Can contain a pointer to an instance of itself (self-referential) • Can declare variables of the structure in the structure definition • Comma-separated list of variable names between closing brace and semicolon • Structure name is optional • Variables of unnamed structures can be declared only by placing them after structure definition, before semicolon

  8. Software Engineering Observation • Provide a structure name when creating a structure type. The structure name is required for declaring new variables of the structure type later in the program, declaring parameters of the structure type and, if the structure is being used like a C++ class, specifying the name of the constructor and destructor.

  9. Structure Definitions (Cont.) • Structures (Cont.) • Built-in operations that may be performed on structure objects • Assignment operator = • Address operator & • Member-access operators . and -> • sizeof operator • Other operators can be overloaded to work with any structure

  10. Structure Definitions (Cont.) • Structures (Cont.) • “Holes” in a structure • Because some computers store data types only on certain memory boundaries • Structure members are not necessarily stored in consecutive memory

  11. Common Programming Error • Comparing structures is a compilation error.

  12. Fig. 22.1| Possible storage alignment for a variable of type Example, showing an undefined area in memory.

  13. Portability Tip • Because the size of data items of a particular type is machine dependent, and because storage alignment considerations are machine dependent, so too is the representation of a structure.

  14. Initializing Structures • Initializing a structure • Structures can be initialized using initializer lists • Example • Card oneCard = { "Three", "Hearts" }; • Initializes member face to "Three" • Initializes member suit to "Hearts" • If there are fewer initializers than members • Remaining members are initialized to default values • Structure variables declared outside any function are initialized to default values • Structure variables may also be initialized by • Assigning a structure variable of the same type • Assigning to individual members

  15. Using Structures with Functions • Passing structures to functions • Entire structure or individual members can be passed to functions • Structures are passed by value, by default • To pass a structure by reference • Pass address of the structure object • Pass reference to the structure object • Pass array of the structure objects • To pass an array by value • Encapsulate it inside a structure, which is passed by value

  16. Performance Tip • Passing structures (and especially large structures) by reference is more efficient than passing them by value (which requires the entire structure to be copied).

  17. typedef • Keyword typedef • Used for creating synonyms for previously defined data types • Often defined to create shorter, simpler or more readable type names • Example • typedef Card *CardPtr; • Defines type name CardPtr as a synonym for Card * • Does not create a new type • Only a new type name that can be used as an alias for an existing type name

  18. Good Programming Practice • Capitalize typedef names to emphasize that these names are synonyms for other type names.

  19. Portability Tip • Synonyms for built-in data types can be created with typedef to make programs more portable. For example, a program can use typedef to create alias Integer for four-byte integers. Integer can then be aliased to int on systems with four-byte integers and can be aliased to long int on systems with two-byte integers where long int values occupy four bytes. Then, the programmer simply declares all four-byte integer variables to be of type Integer.

  20. Outline • DeckOfCards.h • (1 of 1) Define structure Card Class DeckOfCards contains an array of Card structure objects

  21. Outline • DeckOfCards.cpp • (1 of 3)

  22. Outline • DeckOfCards.cpp • (2 of 3) Initialize Card members by assignment

  23. Outline • DeckOfCards.cpp • (3 of 3) Shuffle cards by performing 52 swaps in a single pass of the array

  24. Outline • fig22_04.cpp • (1 of 2)

  25. Outline • fig22_04.cpp • (2 of 2)

  26. 18.1 Introduction (Cont.) • string object • Initialization • string empty(); • Creates an empty string containing no characters • string text( "hello" ); • Creates a string containing the characters "hello" • string name( 8, 'x' ); • Creates a string containing eight 'x' characters • string month = "March"; • Implicitly performs string month( "March" );

  27. 18.1 Introduction (Cont.) • string object (Cont.) • No conversion from int or char in a string definition • Examples (produce syntax errors) • string error1 = 'c'; • string error2( 'u' ); • string error3 = 22; • string error4( 8 ); • Assigning a single character to a string object is allowed • Example • string1 = 'n';

  28. Common Programming Error 18.1 • Attempting to convert an int or char to a string via an initialization in a declaration or via a constructor argument is a compilation error.

  29. 18.1 Introduction • C++ class template basic_string • Provides typical string-manipulation operations • Defined in namespacestd • typedefs • For char • typedef basic_string< char > string; • Also provides one for wchar_t

  30. 18.1 Introduction (Cont.) • string object (Cont.) • Member functions length and size • Return the length of the string • The subscript operator [] • Used to access and modify individual characters • First subscript is 0, last subscript is length() – 1

  31. 18.1 Introduction (Cont.) • string object (Cont.) • Stream extraction operator (>>) • Example • cin >> stringObject; • Input is delimited by white-space characters • Function getline is overloaded for strings • Example • getline( cin, string1 ); • Input is delimited by a newline ( '\n' );

  32. 18.2 string Assignment and Concatenation • Member function assign • Copies the contents of a string into another string • Single-argument version • Copies contents of the string argument into the current string • Three-argument version • Copies a specified range of characters • Example • targetString.assign( sourceString, start, numberOfCharacters );

  33. Outline Fig18_01.cpp (1 of 3) Assign the value of string1 to string2 with the assignment operator Copy string1 into string3 with the assign member function Use the subscript operator to assign to individual characters Use member functions length and at to output the contents of string3 one character at a time

  34. Initialize string4 to the result of concatenating string1 and "apult" using the addition operator + Outline Concatenate string3 and "pet" using the addition assignment operator += Fig18_01.cpp (2 of 3) Concatenate string1 and "acomb" Append the string "comb"(the characters from subscript 4 to the end of string1) to empty stringstring5

  35. Outline Fig18_01.cpp (3 of 3)

  36. 18.2 string Assignment and Concatenation (Cont.) • Member function at • Allows access to individual characters • Much like the subscript operator does • Provides checked access (or range checking) • Going past the end of the string throws an out_of_range exception • Subscript operator does not provide checked access

  37. Common Programming Error 18.2 • Accessing a string subscript outside the bounds of the string using function at is a logic error that causes an out_of_range exception.

  38. Common Programming Error 18.3 • Accessing an element beyond the size of the string using the subscript operator is an unreported logic error.

  39. 18.2 string Assignment and Concatenation (Cont.) • string concatenation • Addition operator and addition assignment operator • Overloaded for string concatenation • Member function append • Single-argument version • Concatenates contents of the string argument to end of the current string • Three-argument version • Concatenates specified range of characters from the string argument to end of the current string

  40. 18.3 Comparing strings • Overloaded comparison operators • Operators ==, !=, <, >, <=, >= are overloaded for strings • All such operators return bool values • Member function compare • Compares the values of two strings • Returns 0 if the strings are equivalent • Returns positive number if the current string is lexicographically greater than the argument string • Returns negative number if the current string is lexicographically less than the argument string

  41. 18.3 Comparing strings (Cont.) • Member function compare (Cont.) • Overloaded versions • With five arguments • First two arguments specify starting subscript and length in the current string • Third argument specifies the comparison string • Last two arguments specify starting subscript and length in the comparison string • With three arguments • First two arguments specify starting subscript and length in the current string • Third argument specifies the comparison string

  42. Outline Fig18_02.cpp (1 of 4) Test string1 against string4 for equality using the overloaded equality operator Test string1 against string4 using the overloaded greater-than operator

  43. Outline Compare string1 to string2 Fig18_02.cpp (2 of 4) Compare "sting" (from string1) to "sting" (from string3)

  44. Outline Compare "Hello" (from string4) to string2 Fig18_02.cpp (3 of 4)

  45. Outline Compare "Hel" (from string2) to string4 Fig18_02.cpp (4 of 4)

  46. 18.4 Substrings • Member function substr • Retrieves a substring from a string • Returns a new string object copied from the source string • First argument • Specifies beginning subscript of desired substring • Second argument • Specifies length of desired substring

  47. Outline Fig18_03.cpp (1 of 1) Retrieve a substring from string1

  48. 18.5 Swapping strings • Member function swap • Swaps contents of the current string and the argument string • Useful for implementing programs that sort strings

  49. Outline Fig18_04.cpp (1 of 1) Swap the values of first and second

  50. 18.6 string Characteristics • Characteristics of strings • Capacity • Number of characters that can be stored without allocating more memory • Must be at least equal to the size, can be greater • Depends on the implementation • Returned by member function capacity • Maximum size • Largest possible size a string can have • If exceeded, a length_error exception is thrown • Returned by member function max_size

More Related