Starting Out with C++, 3 rd Edition 1 Chapter 10 – Characters, Strings, and the string Class.

Slides:



Advertisements
Similar presentations
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Advertisements

Chapter 3 Objects, types, and values Bjarne Stroustrup
Files Used to transfer data to and from disk. Opening an Output File Stream #include // File stream library. ofstream outfile;// Declare file stream variable.
C++ crash course Class 10 practice problems. Pointers The following function is trying to swap the contents of two variables. Why isnt it working? void.
1 A Simple C Program /* Take a number multiply it by 10 and display it */ #include main() { int number, result; printf("Type in a number \n"); scanf("%d",
EC-111 Algorithms & Computing Lecture #8 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
 A string is an array of characters.  Strings must have a 0 or null character after the last character to show where the string ends.  The null character.
Chapter 12 Separate Compilation and Namespaces. Abstract Data Type (ADT) ADT: A data type consisting of data and their behavior. The abstraction is that.
Starting Out with C++, 3 rd Edition 1 Chapter 11 – Structured Data Abstract data types (ADTs) are data types created by the programmer. ADTs have their.
Starting Out with C++, 3 rd Edition 1 Chapter 14 – More About Classes.
Class Scope class Student { private: string id; string firstName, lastName; float gpa; public: void Read() { cin >> id >> firstName >> lastName >> gpa;
Review of Inheritance. 2 Several Levels of Inheritance Base Class B Derived class D Derived class D1.
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
M ANIPULATING S TRINGS Resources [1] Object Oriented Programming with C++ (3 rd Edition) E Balagurusamy [2] Teach Yourself C++ (3 rd Edition) H Schildt.
1 C++ string Class Chapter 6. 2 Agenda String Basics (cin, getline )  string operations mixed I/O using >> & getline() Table Output using setw() Functions.
Copyright  Hannu Laine C++-programming Part 5 Strings.
C++ Basics March 10th. A C++ program //if necessary include headers //#include void main() { //variable declaration //read values input from user //computation.
String in C++. String Series of characters enclosed in double quotes.“Philadelphia University” String can be array of characters ends with null character.
AU/MITM/1.6 By Mohammed A. Saleh 1. Introducing the string Class  Instead of using a character array to hold a string, you can use a type string variable.
Chapter 3. Expressions and Interactivity CSC125 Introduction to C++
1 Class Vehicle #include #define N 10../.. 2 Class Vehicle class vehicle { public: float speed; char colour[N+1]; char make[N+1];
Starting Out with C++, 3 rd Edition 1 Chapter 1. Introduction to Computers and Programming.
EXERCISE IN CLASS CHAPTER 3. PART 1 IDENTIFIER SCENARIO 1 o record1 o 1record o file_3 o return o $tax o Name o name and address o name-and-address o.
CS 240: Data Structures Supplemental: Command Line Input.
1 times table 2 times table 3 times table 4 times table 5 times table
STRINGS & STRING HANDLING FUNCTIONS STRINGS & STRING HANDLING FUNCTIONS.
Chapter 3 Expressions and Interactivity Department of Computer Science Missouri State Univeristy.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter 3 Slides By Dr. Daniyal Alghazzawi.
EGR 2261 Unit 9 Strings and C-Strings  Read Malik, pages in Chapter 7, and pages in Chapter 8.  Homework #9 and Lab #9 due next week.
C++ PROGRAMMING: PROGRAM DESIGN INCLUDING DATA STRUCTURES, FIFTH EDITION Chapter 10: Strings and string type.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Formatting Output.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
1 Simple Input/Output  C++ offers the iostream library, which defines a system of character-oriented Input/Output (I/O) using object oriented programming.
Characters, Strings, And The string Class Chapter 10.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Khalid Rasheed Shaikh Computer Programming Theory 1.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Homework #4: Operator Overloading and Strings By J. H. Wang Apr. 17, 2009.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Chapter -7 Basic function of Input/output system basics and file processing Stream classes : I/O Streams. A stream is a source or destination for collection.
Java and C++ Transitioning. A simple example public class HelloWorldApp { public static void main(String[] args) { //Display the string. System.out.println("Hello.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
Chapter 15 Strings as Character Arrays
$100 $200 $300 $400 $500 $100 $200 $300 $400 $500 $100 $200 $300 $400 $500 $100 $200 $300 $400 $500 $100 $200 $300 $400 $500 $100 $200 $300.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
ENEE150 – 0102 ANDREW GOFFIN Strings. Project 2 Flight Database 4 options:  Print flight  Print airport  Find non-stop flights  Find one-stop flights.
Tables Learning Support
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the differences between text and binary files ❏ To write programs.
Basic concepts of C++ Presented by Prof. Satyajit De
Chapter 10 – Characters and Strings
Chapter 3 L7.
Times Tables.
Null-Terminated Character Arrays
C Characters and Strings – Review Lab assignments
Sequential input and output Operations in file
Functions, Part 2 of 3 Topics Functions That Return a Value
Chapter 3: Input/Output
Chapter 3: Expressions and Interactivity
Programming Assignment 1
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
ECE 103 Engineering Programming Chapter 51 Random Numbers
Fundamental Programming
3 times tables.
6 times tables.
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
Presentation transcript:

Starting Out with C++, 3 rd Edition 1 Chapter 10 – Characters, Strings, and the string Class

Starting Out with C++, 3 rd Edition Character Testing The C++ library provides several macros for testing characters. –Be sure to include ctype.h header file

Starting Out with C++, 3 rd Edition 3 Table 10-1

Starting Out with C++, 3 rd Edition 4 Program 10-1 // This program demonstrates some of the character testing // functions. #include void main(void) { char input; cout << "Enter any character: "; cin.get(input); cout << "The character you entered is: " << input << endl; cout << "Its ASCII code is: " << int(input) << endl;

Starting Out with C++, 3 rd Edition 5 Program continues if (isalpha(input)) cout << "That's an alphabetic character.\n"; if (isdigit(input)) cout << "That's a numeric digit.\n"; if (islower(input)) cout << "The letter you entered is lowercase.\n"; if (isupper(input)) cout << "The letter you entered is uppercase.\n"; if (isspace(input)) cout << "That's a whitespace character.\n"; }

Starting Out with C++, 3 rd Edition 6 Program Output With Example input Enter any character: A [Enter] The character you entered is: A Its ASCII code is: 65 That's an alphabetic character. The letter you entered is uppercase. Program Output With Other Example input Enter any character: 7 [Enter] The character you entered is: 7 Its ASCII code is: 55 That's a numeric digit.

Starting Out with C++, 3 rd Edition 7 Program 10-2 // This program tests a customer number to determine if it is // in the proper format. #include // Function prototype bool testNum(char []); void main(void) { char customer[8]; cout << "Enter a customer number in the form "; cout << "LLLNNNN\n"; cout << "(LLL = letters and NNNN = numbers): "; cin.getline(customer, 8);

Starting Out with C++, 3 rd Edition 8 Program continues if (testNum(customer)) cout << "That's a valid customer number.\n"; else { cout << "That is not the proper format of the "; cout << "customer number.\nHere is an example:\n"; cout << " ABC1234\n"; } // Definition of function testNum. bool testNum(char custNum[]) { // Test the first three characters for alphabetic letters for (int count = 0; count < 3; count++) {

Starting Out with C++, 3 rd Edition 9 Program continues if (!isalpha(custNum[count])) return false; } // Test the last 4 characters for numeric digits for (int count = 3; count < 7; count++) { if (!isdigit(custNum[count])) return false; } return true; }

Starting Out with C++, 3 rd Edition 10 Program Output With Example input Enter a customer number in the form LLLNNNN (LLL = letters and NNNN = numbers): RQS4567 [Enter] That's a valid customer number. Program Output With Other Example input Enter a customer number in the form LLLNNNN (LLL = letters and NNNN = numbers): AX467T9 [Enter] That is not the proper format of the customer number. Here is an example: ABC1234

Starting Out with C++, 3 rd Edition Character Case Conversion The C++ library offers functions for converting a character to upper or lower case. –Be sure to include ctype.h header file

Starting Out with C++, 3 rd Edition 12 Table 10-2

Starting Out with C++, 3 rd Edition 13 Program 10-3 // This program calculates the area of a circle. It asks the // user if he or she wishes to continue. A loop that // demonstrates the toupper function repeats until the user // enters 'y', 'Y', 'n', or 'N'. #include void main(void) { const float pi = ; float radius; char go; cout << "This program calculates the area of a circle.\n"; cout.precision(2); cout.setf(ios::fixed);

Starting Out with C++, 3 rd Edition 14 Program continues do { cout << "Enter the circle's radius: "; cin >> radius; cout << "The area is " << (pi * radius * radius); cout << endl; do { cout << "Calculate another? (Y or N) "; cin >> go; } while (toupper(go) != 'Y' && toupper(go) != 'N'); } while (toupper(go) == 'Y'); }

Starting Out with C++, 3 rd Edition 15 Program Output With Example input This program calculates the area of a circle. Enter the circle's radius: 10 [Enter] The area is Calculate another? (Y or N) b Enter] Calculate another? (Y or N) y [Enter] Enter the circle's radius: 1 [Enter] The area is 3.14 Calculate another? (Y or N) n [Enter]

Starting Out with C++, 3 rd Edition Review of the Internal Storage of C-strings A C-string is a sequence of characters stored in consecutive memory locations, terminated by a null character. Figure 10-1

Starting Out with C++, 3 rd Edition 17 Program 10-4 // This program contains string constants #include void main(void) { char again; do { cout << "C++ programming is great fun!" << endl; cout << "Do you want to see the message again? "; cin >> again; } while (again == 'Y' || again == 'y'); }

Starting Out with C++, 3 rd Edition 18 Program 10-5 // This program cycles through a character array, displaying // each element until a null terminator is encountered. #include void main(void) { char line[80]; int count = 0; cout << "Enter a sentence of no more than 79 characters:\n"; cin.getline(line, 80); cout << "The sentence you entered is:\n"; while (line[count] != '\0') { cout << line[count]; count++; }

Starting Out with C++, 3 rd Edition 19 Program Output with Example input Enter a sentence of no more than 79 characters: C++ is challenging but fun! [Enter] The sentence you entered is: C++ is challenging but fun!

Starting Out with C++, 3 rd Edition Library Functions for Working with C-strings The C++ library has numerous functions for handling C-strings These functions perform various tests and manipulations. Functions discussed in this section require the inclusion of string.h header file

Starting Out with C++, 3 rd Edition 21 Figure 10-2

Starting Out with C++, 3 rd Edition 22 Table 10-3

Starting Out with C++, 3 rd Edition 23 Program 10-6 // This program uses the strstr function to search an array // of strings for a name. #include #include // For strstr void main(void) { char prods[5][27] = {"TV inch Television", "CD257 CD Player", "TA677 Answering Machine", "CS109 Car Stereo", "PC955 Personal Computer"}; char lookUp[27], *strPtr = NULL; int index;

Starting Out with C++, 3 rd Edition 24 Program continues cout << "\tProduct Database\n\n"; cout << "Enter a product number to search for: "; cin.getline(lookUp, 27); for (index = 0; index < 5; index++) { strPtr = strstr(prods[index], lookUp); if (strPtr != NULL) break; } if (strPtr == NULL) cout << "No matching product was found.\n"; else cout << prods[index] << endl; }

Starting Out with C++, 3 rd Edition 25 Program Output With Example input Product Database Enter a product to search for: CD257 [Enter] CD257 CD Player Program Output With Example input Product Database Enter a product to search for: CS [Enter] CS109 Car Stereo Program Output With Other Example input Product Database Enter a product to search for: AB [Enter] No matching product was found.

Starting Out with C++, 3 rd Edition String/Numeric Conversion Functions The C++ library provides functions for converting a C-string representation of a number to a numeric data type, and vice- versa. The functions in this section require the stdlib.h file to be included.

Starting Out with C++, 3 rd Edition 27 Table 10-4

Starting Out with C++, 3 rd Edition 28 Table 10-4 Continued Function Description itoa Converts an integer to a C-string. The first argument, value, is the integer. The result will be stored at the location pointed to by the second argument, string. The third argument, base, is an integer. It specifies the numbering system that the converted integer should be expressed in. ( 8 = octal, 10 = decimal, 16 = hexadecimal, etc. ) Example Usage: itoa(value, string, base)

Starting Out with C++, 3 rd Edition 29 Program 10-7 // This program demonstrates the strcmp and atoi functions. #include #include // For strcmp #include // For atoi void main(void) { char input[20]; int total = 0, count = 0; float average; cout << "This program will average a series of numbers.\n"; cout << "Enter the first number or Q to quit: "; cin.getline(input, 20);

Starting Out with C++, 3 rd Edition 30 Program continues while ((strcmp(input, "Q") != 0)&&(strcmp(input, "q") != 0)) { total += atoi(input); // Keep a running total count++; // Keep track of how many numbers entered cout << "Enter the next number or Q to quit: "; cin.getline(input, 20); } if (count != 0) { average = total / count; cout << "Average: " << average << endl; }

Starting Out with C++, 3 rd Edition 31 Program Output With Example input This program will average a series of numbers. Enter the first number or Q to quit: 74 [Enter] Enter the next number or Q to quit: 98 [Enter] Enter the next number or Q to quit: 23 [Enter] Enter the next number or Q to quit: 54 [Enter] Enter the next number or Q to quit: Q [Enter] Average: 62

Starting Out with C++, 3 rd Edition Focus on Software Engineering: Writing Your Own C-string-Handling Functions You can design your own specialized functions for manipulating C-strings.

Starting Out with C++, 3 rd Edition 33 Program 10-8 // This program uses a function to copy a C-string into an array. #include void stringCopy(char [], char []); // Function prototype void main(void) { char first[30], second[30]; cout << "Enter a string with no more than 29 characters:\n"; cin.getline(first, 30); stringCopy(first, second); cout << "The string you entered is:\n" << second << endl; }

Starting Out with C++, 3 rd Edition 34 Program continues // Definition of the stringCopy function. // This function accepts two character arrays as // arguments. The function assumes the two arrays // contain C-strings. The contents of the second array is // copied to the first array. void stringCopy(char string1[], char string2[]) { int index = 0; while (string1[index] != '\0') { string2[index] = string1[index]; index++; } string2[index] = '\0'; }

Starting Out with C++, 3 rd Edition 35 Program Output With Example input Enter a string with no more than 29 characters: Thank goodness it’s Friday! [Enter] The string you entered is: Thank goodness it's Friday!

Starting Out with C++, 3 rd Edition 36 Program 10-9 // This program uses the function nameSlice to "cut" the last // name off of a string that contains the user's first and // last names. #include void nameSlice(char []);// Function prototype void main(void) { char name[41]; cout << "Enter your first and last names, separated "; cout << "by a space:\n"; cin.getline(name, 41); nameSlice(name); cout << "Your first name is: " << name << endl; }

Starting Out with C++, 3 rd Edition 37 Program continues // Definition of function nameSlice. This function accepts a // character array as its argument. It scans the array looking // for a space. When it finds one, it replaces it with a null // terminator. void nameSlice(char userName[]) { int count = 0; while (userName[count] != ' ' && userName[count] != '\0') count++; if (userName[count] == ' ') userName[count] = '\0'; }

Starting Out with C++, 3 rd Edition 38 Program Output With Example input Enter your first and last names, separated by a space: Jimmy Jones [Enter] Your first name is: Jimmy

Starting Out with C++, 3 rd Edition 39 Figure 10-3

Starting Out with C++, 3 rd Edition 40 Figure 10-4

Starting Out with C++, 3 rd Edition 41 Using Pointers to pass C-string arguments Very useful Can assume string exists from address pointed to by the pointer up to the ‘\0’

Starting Out with C++, 3 rd Edition 42 Program // This program demonstrates a function, countChars, that counts // the number of times a specific character appears in a string. #include // Function prototype int countChars(char *, char); void main(void) { char userString[51], letter; cout << "Enter a string (up to 50 characters): "; cin.getline(userString, 51); cout << "Enter a character and I will tell you how many\n"; cout << "times it appears in the string: "; cin >> letter; cout << letter << " appears "; cout << countChars(userString, letter) << " times.\n"; }

Starting Out with C++, 3 rd Edition 43 Program continues // Definition of countChars. The parameter strPtr is a pointer // that points to a string. The parameter ch is a character that // the function searches for in the string. The function returns // the number of times the character appears in the string. int countChars(char *strPtr, char ch) { int times = 0; while (*strPtr != '\0') { if (*strPtr == ch) times++; strPtr++; } return times; }

Starting Out with C++, 3 rd Edition 44 Program Output With Example input Enter a string (up to 50 characters):Starting Out With C++ [Enter] Enter a character and I will tell you how many times it appears in the string: t [Enter] t appears 4 times.

Starting Out with C++, 3 rd Edition 45 The C++ string Class Offers “ease of programming” advantages over the use of C-strings Need to #include the string header file (Notice there is no.h extension.) Use the following statement after the #include statements: using namespace std;

Starting Out with C++, 3 rd Edition 46 Program // This program demonstrates the C++ string class. #include #include // Required for the string class using namespace std; void main(void) { string movieTitle; string name("William Smith"); movieTitle = "Wheels of Fury"; cout << "My favorite movie is " << movieTitle << endl; } Program output My favorite movie is Wheels of Fury

Starting Out with C++, 3 rd Edition 47 A note about the iostream header file The preceding program uses the iostream header, not iostream.h. With some compilers, you must include the iostream header instead of iostream.h when using cout and cin with string objects.

Starting Out with C++, 3 rd Edition 48 Program 10-13: Using cin with a string object // This program demonstrates how cin can read a string into // a string class object. #include using namespace std; void main(void) { string name; cout << "What is your name? " << endl; cin >> name; cout << "Good morning " << name << endl; }

Starting Out with C++, 3 rd Edition 49 Program Output With Example Input What is your name? Peggy Good morning Peggy

Starting Out with C++, 3 rd Edition 50 Reading a line of input into a string class object Use the getline function to read a line of input, with spaces, into a string object. Example code: string name; cout << “What is your name? “; getline(cin, name);

Starting Out with C++, 3 rd Edition 51 Comparing and Sorting string Objects You may use the relational operators to compare string objects: = == !=

Starting Out with C++, 3 rd Edition 52 Program // This program uses the == operator to compare the string entered // by the user with the valid stereo part numbers. #include #include using namespace std; void main(void) { const float aprice = 249.0, bprice = 299.0; string partNum; cout > partNum; cout.setf(ios::fixed | ios::showpoint); cout.precision(2);

Starting Out with C++, 3 rd Edition 53 Program (continued) if (partNum == "S147-29A") cout << "The price is $" << aprice << endl; else if (partNum == "S147-29B") cout << "The price is $" << bprice << endl; else cout << partNum << " is not a valid part number.\n"; } Program Output The stereo part numbers are: Boom Box, part number S147-29A Shelf Model, part number S147-29B Enter the part number of the stereo you wish to purchase: S147-29A [Enter] The price is $249.00

Starting Out with C++, 3 rd Edition 54 Other Ways to Declare string Objects Declaration ExampleDescription string address Declares an empty string object named address. string name(“Bill Smith”); name is a string object initialized with “Bill Smith” string person1(person2); person1 is initialized with a copy of person2. person2 may be either a string object or a char array. See Table 10-8 (page 589) for more examples.

Starting Out with C++, 3 rd Edition 55 Table Other Supported Operators >> Extracts characters from a stream and inserts them into a string. Characters are copied until a whitespace or the end of the string is encountered. << Inserts a string into a stream. = Assigns the string on the right to the string object on the left. += Appends a copy of the string on the right to the string object on the left. + Returns a string that is the concatenation of the two string operands. [] Implements array-subscript notation, as in name[x]. A reference to the character in the x position is returned.

Starting Out with C++, 3 rd Edition 56 Program // This program demonstrates the C++ string class. #include using namespace std; void main(void) { string str1, str2, str3; str1 = "ABC"; str2 = "DEF"; str3 = str1 + str2; cout << str1 << endl; cout << str2 << endl; cout << str3 << endl; str3 += "GHI"; cout << str3 << endl; }

Starting Out with C++, 3 rd Edition 57 Program Output ABC DEF ABCDEF ABCDEFGHI

Starting Out with C++, 3 rd Edition 58 string class member functions Many member functions exist. See Table (pages )