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.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
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.
Character and String definitions, algorithms, library functions Characters and Strings.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Chapter 10.
Starting Out with C++, 3 rd Edition 1 Chapter 5. Looping.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
 Monday, 9/30/02, Slide #1 CS106 Introduction to CS1 Monday, 9/30/02  QUESTIONS (on HW02, etc.)??  Today: Libraries, program design  More on Functions!
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
String What it is Why it’s useful library routines for handling strings how to input a string from the keyboard.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
1 Chapter 10 Characters, Strings, and the string class.
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
CHAPTER 8 CHARACTER AND STRINGS
Lecture 17: Characters, Strings, and the string class Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
CS102 Introduction to Computer Programming Chapter 10 Characters and Strings.
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.
ARRAYS Lecture 2. 2 Arrays Hold Multiple values  Unlike regular variables, arrays can hold multiple values.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
STARTING OUT WITH STARTING OUT WITH Class 9 Honors.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. 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).
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Characters and Strings Functions.
Chapter Characters, Strings, and the string class 10.
Characters and Strings
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
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.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
C Characters and Strings
Fundamentals of Characters and Strings
Chapter 7 – Arrays.
Chapter 3. Expressions and Interactivity
Chapter 1. Introduction to Computers and Programming
Characters, C-Strings, and More About the string Class
A First Book of ANSI C Fourth Edition
Chapter 5. Looping.
Chapter 8 - Characters and Strings
Standard Version of Starting Out with C++, 4th Edition
Starting Out with C++: From Control Structures through Objects
Popping Items Off a Stack Lesson xx
Chapter 5. Looping.
C Characters and Strings – Review Lab assignments
String What it is Why it’s useful
Standard Version of Starting Out with C++, 4th Edition
Arrays Arrays A few types Structures of related data items
C++ Programming Lecture 20 Strings
Characters and Strings Functions
C Characters and Strings
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Chapter 10 – Characters and Strings

10.1 Character Testing The C++ library provides macros for testing characters. Be sure to include ctype.h

Table 10-1

Program 10-1 // This program demonstrates some of the character testing // macros. #include <iostream.h> #include <ctype.h> 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;

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

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.

Program 10-2 // This program tests a customer number to determine if it is // in the proper format. #include <iostream.h> #include <ctype.h> // 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);

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. int TestNum(char CustNum[]) // Test the first three characters for alphabetic letters for (int Count = 0; Count < 3; Count++)

Program continues 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 1;

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 (LLL = letters and NNNN = numbers): AX467T9 [Enter] That is not the proper format of the customer number. Here is an example: ABC1234

10.2 Character Case Conversion The C++ library offers functions for converting a character to upper or lower case. Be sure to include ctype.h

Table 10-2

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 <iostream.h> #include <ctype.h> void main(void) { const float Pi = 3.14159; float Radius; char Go; cout << "This program calculates the area of a circle.\n"; cout.precision(2); cout.setf(ios::fixed);

Program continues do { cout << "Enter the circle's radius: "; cin >> Radius; cout << "The area is " << (Pi * Radius * Radius); cout << endl; 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 314.16 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]

10.3 Review of the Internal Storage of Strings In C++, a sting is a sequence of characters stored in consecutive memory locations, terminated by a null character. Figure 10-1

Program 10-4 // This program contains string constants #include <iostream.h> 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'); }

Program 10-5 // This program cycles through a character array, displaying // each element until a null terminator is encountered. #include <iostream.h> 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 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!

10.4 Library Functions for Working with Strings The C++ library has numerous functions for handling string.s These functions perform various tests and manipulations. Functions discussed in this section require the inclusion of string.h

Figure 10-2

Table 10-3

Program 10-6 // This program uses the strstr function to search an array // of strings for a name. #include <iostream.h> #include <string.h> // For strstr void main(void) { char Prods[5][27] = {"TV327 31 inch Television", "CD257 CD Player", "TA677 Answering Machine", "CS109 Car Stereo", "PC955 Personal Computer"}; char LookUp[27], *StrPtr = NULL; int Index;

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;

Program Output With Example Input Product Database Enter a product to search for: CD257 [Enter] CD257 CD Player Program Output With Example Input Enter a product to search for: CS [Enter] CS109 Car Stereo Program Output With Other Example Input Enter a product to search for: AB [Enter] No matching product was found.

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.h file to be included.

Table 10-4

Program 10-7 // This program demonstrates the strcmp and atoi functions. #include <iostream.h> #include <string.h> // For strcmp #include <stdlib.h> // 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);

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;

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

10.6 Focus on Software Engineering: Writing Your Own String-Handling Functions You can design your own specialized functions for manipulating strings.

Program 10-8 // This program uses a function to copy a string into an array. #include <iostream.h> 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; }

Program continues void StringCopy(char String1[], char String2[]) { int Index = 0; while (String1[Index] != '\0') String2[Index] = String1[Index]; Index++; } String2[Index] = '\0';

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!

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 <iostream.h> 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; }

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

Program Output With Example Input Enter your first and last names, separated by a space: Jimmy Jones [Enter] Your first name is: Jimmy

Figure 10-3

Figure 10-4

Program 10-10 // This program demonstrates a function, CountChars, that counts // the number of times a specific character appears in a string. #include <iostream.h> // 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"; }

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;

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.