CS102 Introduction to Computer Programming Chapter 10 Characters and Strings.

Slides:



Advertisements
Similar presentations
EC-111 Algorithms & Computing Lecture #11 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Advertisements

C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Lesson 10 Characters, C-Strings, and the string Class CS1 Lesson John Cole1.
Chapter 10.
1 9/10/07CS150 Introduction to Computer Science 1 Data Types Section 2.7 – 2.12 CS 150 Introduction to Computer Science I.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
C-Strings A C-string (also called a character string) is a sequence of contiguous characters in memory terminated by the NUL character '\0'. C-strings.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
CS Nov 2006 C-strings.
Chapter 2: Introduction to C++.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 12 More.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
1 Chapter 10 Characters, Strings, and the string class.
In Addition... To the string class from the standard library accessed by #include C++ also has another library of string functions for C strings that can.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Lecture 17: Characters, Strings, and the string class Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
February 14, 2005 Characters, Strings and the String Class.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Chapter 10. Characters, Strings and the string class Csc 125 Introduction to C++ Fall 2005.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
STARTING OUT WITH STARTING OUT WITH Class 9 Honors.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10: Characters, Strings, and the string class.
Characters, Strings, And The string Class Chapter 10.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 10: Characters, C- Strings, and More About.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
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
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
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).
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter Characters, Strings, and the string class 10.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Strings, and the string Class. C-Strings C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character The C-string.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
Chapter 10 – Characters and Strings
Characters, C-Strings, and More About the string Class
Standard Version of Starting Out with C++, 4th Edition
Starting Out with C++: From Control Structures through Objects
Engineering Problem Solving with C++, Etter
Chapter 2: Introduction to C++.
Standard Version of Starting Out with C++, 4th Edition
C++ Programming Lecture 20 Strings
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

CS102 Introduction to Computer Programming Chapter 10 Characters and Strings

Topics for Discussion Character Testing Character Case Conversion Review of the Internal Storage of Strings Strings Stored in Arrays Library Functions for Working With Arrays String Numeric Conversion Functions Writing String Handling Functions

Character Testing In C a macro is a #define that takes arguments –It behaves like a function call –When a macro is called it is inserted directly into the program –Replaced in C++ by the inline function Include the ctype.h header for the following macros: Concept - The C++ Library provides macros for testing characters

#include isalphareturns True if a letter of the alphabet isalnumreturns True if a letter or number 0-9 isdigitreturns True if a number 0-9 islowerreturns True if a lower case letter isprintreturns True if a printable character ispunctreturns True if a printable character other than a letter or digit or space isupperreturns True if a uppercase letter isspacereturns True if a white space character –space' ' –newline'\n' –vertical tab'\v ' –tab'\t'

Program 10-1 /* This program demonstrates some of the character testing macros. */ #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; 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"; } Program Output 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 Enter any character: 7 [Enter] The character you entered is: 7 Its ASCII code is: 55 That's a numeric digit.

Program 10-2 /* This program tests a customer number to determine if it is in the proper format.*/ #include // Function prototype int 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); 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"; }

Program 10-2 // Definition of function TestNum. int TestNum(char CustNum[]) { // Test the first three characters for letters for (int Count = 0; Count < 3; Count++) { if (!isalpha(CustNum[Count])) return 0; } // Test the last 4 characters for numeric digits for (int Count = 3; Count < 7; Count++) { if (!isdigit(CustNum[Count])) return 0; } return 1; } Program Output 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

Character Case Conversion Touppper (tolower) –accepts a single character as an argument –if the character is lower case(upper case) it returns the upper case(lower case) equivalent –if is already upper case(lower case) or not a letter the original value is returned Call by value. The argument is not changed Must include ctype.h Concept - The C++ Library provides functions for converting a character to upper or lower case.

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); 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'); }

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]

Internal Storage of Strings Review The null character '\0' is used to terminate a character string A string constant is any literal string enclosed in " " –it has its own storage location just like the variables of an array A string stored in an array can be processed using standard subscript notation. Concept - In C++, a string is a sequence of characters stored in consecutive memory locations, terminated by a null character.

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++; } Program Output 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!

String Manipulators Review cin can be used to input a character string with no white space characters cin >>last_name; Edwards cin.getline can be used input a character string with spaces into an array cin.getline(name,20); Daniel Edwards cin.get can be use to input a single character of any type cin.get(ch); Enter

Strings Stored in Arrays There is no data type for string variables. –Character strings can be stored in character arrays There is no boundary checking for Strings. –Be sure the array is large enough to hold the null terminator An array name with no [ ] and subscripts is the address of the first element of the array. array = = &array[0] is true A string stored in an array can be processed using standard subscript notation.

Library Functions for Working With Character Arrays strlenreturns the length of a string not including the null terminator int len; char Name[] ="Francis"; len = strlen (Name); cout << len; 7 strcatappends the contents of one string to another char First[13] ="Francis", Second [] = "Bacon" ; strcat (First, Second); cout <<First <<" "<<Second;FrancisBacon Bacon strcpycopies one string to another char First[14] = "Francis", Name [] = "Francis Bacon" strcpy (First, Name) cout <<First <<" " <<Name;Francis Bacon Francis Bacon

Library Functions for Working With Character Arrays strncpycopies a specified number of characters from string2 to string1 char First [8], Name[] = "Francis Bacon"; strncpy (first, Name, 7); cout << First <<" " <<Name;Francis Francis Bacon strcmpcompares the contents of two strings. returns 0 if string2 = = string1 returns negative if string2 is > string 1 returns positive if string2 is < string 1 strstrsearches a string for the location of another string char Name[] = "Francis Bacon", Second[] = "Bacon" ; cout <<strstr (Name, Second);Bacon (because cout displays the string if given an address)

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; 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; }

Program Output 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.

Differences Between Strings and Numbers There is a difference between numbers stored as strings and numbers stored as numeric values. –A character string of digits isn't a number but a series of ASCII codes. mathematical operations can not be performed on it –It uses 1 byte of memory for each digit. an int data type takes 2 bytes for the whole number The C++ library provides functions for converting a string representation of a number to a numeric data type and vice- versa.

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

String Numeric Conversion Functions atoiconverts a string of digits into an integer. atolconverts a string of digits into a long integer. atofconverts a string of digits into a floating point number. itoaconverts an integer into a character string and stores it in an array. Caution: make sure the array is large enough to hold all the characters plus the null terminator.

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); 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; }

Program Output 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

The C++ string Class Offers “ease of programming” advantages over the use of C-strings Need to #include the string header file

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

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; }

Program Output With Example Input What is your name? Peggy Good morning Peggy

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

Comparing and Sorting string Objects You may use the relational operators to compare string objects: = == !=

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 << fixed << showpoint << precision(2);

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

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.

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.

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; }

Program Output ABC DEF ABCDEF ABCDEFGHI

string class member functions Many member functions exist. See Table (pages )