System Design and Programming II

Similar documents
Chapter 10 Characters, Strings, and the string class

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Chapter 10: Characters, C- Strings, and More About the string Class Character Testing

Chapter 10: Character Testing. From Program Character Case Conversion 8/23/2014. Character Testing. Character Case Conversion

Chapter 10: Characters, C- Strings, and More About the string Class

C-String Library Functions

Chapter 8 - Characters and Strings

C: How to Program. Week /May/28

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Scientific Programming in C V. Strings

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

Chapter 8: Character & String. In this chapter, you ll learn about;

Chapter 8 C Characters and Strings

Fundamentals of Programming. Lecture 11: C Characters and Strings

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

C mini reference. 5 Binary numbers 12

LECTURE 15. String I/O and cstring library

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Introduction to string

Strings in C++ Dr. Ferdin Joe John Joseph Kamnoetvidya Science Academy

Structured programming

BITG 1113: Array (Part 2) LECTURE 9

Characters and Strings

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

Engineering Problem Solving with C++, Etter

C Libraries. Bart Childs Complementary to the text(s)

Topic 3. Big C++ by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

The C++ Language. Arizona State University 1

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

Strings and Stream I/O

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Week 2. Muhao Chen.

CS 115 Exam 3, Spring 2010

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

BITG 1233: Introduction to C++

today cs3157-fall2002-sklar-lect05 1

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

LECTURE 02 INTRODUCTION TO C++

Copyright 2003 Pearson Education, Inc. Slide 1

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

2 nd Week Lecture Notes

Object Oriented Programming COP3330 / CGS5409

Objectives. In this chapter, you will:

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 11, FALL 2012

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

In this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

Computer Programming

Strings and Library Functions

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Contents. Preface. Introduction. Introduction to C Programming

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

CSCE 110 PROGRAMMING FUNDAMENTALS

REVIEW. The C++ Programming Language. CS 151 Review #2

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

CS107 Spring 2019, Lecture 4 C Strings


CS107, Lecture 4 C Strings

Chapter Two MULTIPLE CHOICE

! A C-string is a sequence of characters stored in consecutive memory locations and terminated by a null character ( \0').

CHAPTER 3 BASIC INSTRUCTION OF C++

ONE DIMENSIONAL ARRAYS

by Pearson Education, Inc. All Rights Reserved.

Fundamentals of Programming CS-110. Lecture 2

ROCK PAPER SCISSORS Rock Paper Scissors Lab Project Using C or C++

Appendix A. ASCII Character Set

Lecture 12. We have already used strings. Strings. Hello Class is a string.

A First Program - Greeting.cpp

Outline. Computer Programming. Structure of a function. Functions. Function prototype. Structure of a function. Functions

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Exercise 1.1 Hello world

C++ Quick Reference. switch Statements

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

CISC 1110 (CIS 1.5) Introduc2on to Programming Using C++

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Chapter 9 Strings. With this array declaration: char s[10];

Name. CPTR246 Spring '17 (100 total points) Exam 2

Arrays, Strings, & Pointers

Introduction to Programming EC-105. Lecture 2

Decisions. Arizona State University 1

Computer Science XII Important Concepts for CBSE Examination Questions

Chapter 8 Character Arrays and Strings

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

CMSC 202 Midterm Exam 1 Fall 2015

Transcription:

System Design and Programming II CSCI 194 Section 01 CRN: 10968 Fall 2017 David L. Sylvester, Sr., Assistant Professor

Chapter 10 Characters, Strings, and the string Class

Character Testing The C++ library provides several functions for testing characters. To use these functions you must include the cctype header file. These libraries provide several functions that allow you to test the value of a character. These functions test a single char argument and return either true or false. They actually return an int value (0 false, nonzero true). Ex: char letter = a ; if (isupper(letter)); else cout << Letter is uppercase.\n ; cout << Letter is lowercase.\n ; will output Letter is lowercase.

Character Testing Functions Character Function isalpha isalnum isdigit islower isprint ispunct isupper isspace Description Returns true ( nonzero number) if the argument is a letter of the alphabet. Return 0 if the argument is not a letter Returns true (nonzero number) if the argument is a letter of the alphabet or a number. Otherwise, it returns 0. Returns true ( nonzero number) if the argument is a digit from 0 through 9. Otherwise, it returns 0. Returns true (nonzero number) if the argument is a lowercase letter. Otherwise, it returns 0. Returns true (nonzero number) if the argument is a printable character (including a space). Otherwise, it returns 0. Returns true (nonzero number) if the argument is a printable character other than a digit, letter or space. Otherwise, it returns 0. Returns true (nonzero number) if the argument is an uppercase letter. Otherwise, it returns 0. Returns true (nonzero number) if the argument is a whitespace character. ( i.e. space, vertical tab \v, newline \n, tab \t ). Otherwise, it returns 0.

Character Functions Sample Program #include <iostream> // This program demonstrates some // character-testing functions. #include <iostream> #include <cctype> using namespace std; int main() { char input; cout << Enter any character: "; cin.get(input); cout << "The character you entered is: " << 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"; return 0; }

Character Functions Sample Program // This program test a customer number // to determine whether it is in the // proper format. #include <iostream> #include <cctype> using namespace std; } } cout << "That is not the proper format for the "; cout << "customer number.\nhere is an example\n"; cout << " ABC1234\n"; return 0; // Function prototype bool testnum(char[], int); int main() { const int SIZE = 8;// Array size char customer[size];// To hold a customer number // Get the customer number. cout << "Enter a customer number in the form "; cout << "LLLNNNN\n"; cout << "(LLL = letters and NNNN = numbers): "; cin.getline(customer, SIZE); // Determine whether it is valid. if (testnum(customer, SIZE)) cout << "That's a valid customer number.\n"; else { // Definition of Function testnum. bool testnum(char custnum[], int size) { int count;// Loop counter } // Test the first three characters for alphabetic letters. for (count = 0; count < 3; count++) { if (!isalpha(custnum[count])) } return false; // Test the remaining characters for numeric digits. for (count = 3; count < size -1; count++) { if (!isdigit(custnum[count])) return false; } return true;

Character Case Conversion The C++ library provides two functions, toupper and tolower, for converting the case of a character. These functions are also prototyped in the header file cctype, so be sure to include it. Additional Character Functions toupper tolower Returns the uppercase equivalent of its argument. Returns the lowercase equivalent of its argument. Note: These functions accept a single character argument. Ex: cout << toupper ( a ); outputs A If the argument is already an uppercase letter, toupper return is unchanged. Any nonletter argument passed to toupper is returned as it is.

Ex: cout << toupper( * ) // Displays * cout << toupper( & ) // Displays & cout << toupper( % ) // Displays % toupper and tolower do not actually cause the character argument to change (change the stored value), they simply return the upper or lower equivalent of the argument. Ex: char letter = A ; cout << tolower(letter) << endl; cout << letter; Will output a Will output A

Character Functions Sample Program // 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' or 'n', 'N'. #include <iostream> #include <cctype> #include <iomanip> using namespace std; char goagain;// To hold Y or N int main() { const double PI = 3.14159;// Constant for pi double radius;// The circle's radius cout << "This program calculates the area of a circle.\n"; cout << fixed << setprecision(2); { do // Get the radius and display the area. cout << "Enter the circle's radius: "; cin >>radius; cout << "The area is "<< (PI * radius * radius); cout << endl; // Does the user want to do this again? cout << "Calculate another? (Y or N) "; cin >> goagain; // Validate the input. while (toupper(goagain)!= 'Y' && toupper(goagain) { }!= 'N') cout << "Please enter Y or N: "; cin >> goagain; Prompts the user for the radius Calculates and output area of circle Makes only 2 comparison rather than 4 (Y,y,N,n) } } while (toupper(goagain) == 'Y'); return 0;

Review of the Internal Storage of C-Strings String in a generic term that describes any consecutive sequence of characters. Ex: word sentence Have a nice day. person s name title of a song A string may be constant or variable in nature, and may be stored in a variety of ways. C-strings describes a string whose characters are stored in consecutive memory locations and are followed by a null character, or null terminator. The null terminator marks the end of the C-string. Without it a function has no way of knowing the length of a C-string argument. T O M O R R O W \0

String Literals A string literal or string constant is enclosed in a set of double quotes. Ex: Have a nice day. What is your name? John Smith Please enter your age: Part Number 45q1798 All of a program s string literals are stored in memory as C- strings, with the null terminator automatically appended.

Character Functions Sample Program // This program contains string literals. #include <iostream> using namespace std; int main() { 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'); return 0; Although the strings are not stored in arrays, they are still part of the program s data. The first string occupies 30 bytes of memory and the second occupies 39 bytes. Both sizes include the null terminator. } 2 string literals

The string literals on the previous page would be represented as such: C + + p r o g r a m m i n g i s g r e a t f u n! \0 D o y o u w a n t t o s e e t h e m e s s a g e a g a i n? \0 It is important to realize that a string literal has its own storage location, just like a variable or an array. When a string literal appears in a statement, it s actually its memory address that C++ uses. Ex: cout << Do you want to see the message again? ; In this statement, the memory address of the string literal Do you want to see the message again? is passed to the cout object. cout displays the consecutive characters found in this address and stop displaying characters when a null terminator is encountered.

Strings Stored in Array When defining a character array for holding a C-string, be sure the array is large enough for the null terminator. Ex: char company[12] // holds no more than 11 characters String input can be performed by using the cin object. It allows a string to be entered that has no whitespace characters into the company array. If a user enters more than 11 characters, cin will write past the end of the array, because it has no way of knowing that the variable company has 12 elements. Ex: cin >> company Because company is an array and is being used without the brackets or subscripts, it indicate the address in memory where string is to be stored.

The cin problem can be solved by using the cin s getline member function. Ex: char line[80]; cin.getline(line,80); Gets a line of input (including whitespace characters) and store it in the line array. Starting address of line array Number of character to accept including null terminator. cin will read 79 characters, or until the user presses the [ENTER] key, whichever comes first. cin will automatically append the null terminator.

Sample Program // This program displays a string stored // in a char array. #include <iostream> using namespace std; int main() { const int SIZE = 80;// Array size char line[size];// To hold a line of input int count = 0;// Loop counter variable // Get a line of input. cout << "Enter a sentence of no more than " << (SIZE - 1) << " characters.\n"; cin.getline(line,80); } // display the input one character at a time. cout << "The sentence you entered is:\n"; while(line[count]!= '\0') { } cout << line[count]; count ++; return 0;

Library Functions for Working with C-strings The C++ library has numerous functions for handling C-strings. They perform various tests and manipulations, and require that the cstring header file be included. Function Description (*Accepts 1 C-string or pointer; **Accepts 2 C-strings or pointers to a C-string) * ** ** ** ** ** ** strlen strcat strcpy strncat strncpy strcmp strstr Returns the length of the C-string (not including the null terminator) Ex: len = strlen(name); Appends the contents of the second string to the first C-string. (The first string is altered, the second string is unchanged.) Ex: strcat(string1, string2); Copies the second C-string to the first C-string. The second is unchanged. Ex: strcpy(string1, string2); The third argument, an integer, indicates the maximum number of characters to copy from the second C-string to the first C-string. Ex: strncat(string1, string2, n); The third argument, an integer, indicates the maximum number of characters to copy from the second C-string to the first C-string. (string1 padded with \0 if n > string 2; Ex: strncpy(string1, string2, n); If string1 and string2 are the same, returns 0. If string2 alphabetically greater will return -1, if string 2 alphabetically less than it will return 1. Ex: if (strcmp(string1, string2)) Searches for the first occurrence of string2 in string1. If found returns a pointer to it. Otherwise returns a NULL pointer (address 0) Ex: cout << strstr(string1, string2);

Ex: The strlen Function char name[50] = Thomas Edison ; int length; length = strlen(name); The strlen function accepts a pointer to a C-string as its argument. It returns the length of the string, which is the number of characters up to, but not including the null terminator. The variable length will have the value integer value 13. Note: Do not confuse the length of the string with the size of the array. The only information being passed to strlen is the beginning address of a C-string. It does not know where the array ends, so it looks for the null terminator to indicate the end of the string. Using strlen with a literal string. Ex: length = strlen( Thomas Edison );

The strcat Function The strcat function concatenates, or appends one string to another. Appends string1 with string2 Ex: char string1[13] = Hello ; char string2[7] = World! ; cout << string1 << endl; cout << string2 << endl; strcat(string1, string2); cout << string1; Code produces this output Hello World! Hello World! string1 H e l l o \0 string2 W o r l d! \0 string1 after strcat is executed H e l l o W o r l d! \0 string2 after strcat is executed (unchanged) W o r l d! \0

Sample program segment that uses sizeof operator to test an array s size before strcat is called. Returns value of the size of the array Return size of string stored in string1 array Return size of string stored in string1 array Accounts for null terminator if (sizeof(string1) >= (strlen(string1) + strlen(string2) + 1)) strcat(string1, string2); else cout << String1 is not large enough for both strings.\n ;

The strcpy Function Unlike copying arrays where you have to copy one element at a time, usually using a for loop, with strings the strcpy function can be used to copy one string into another. Ex: char name[20]; strcpy(name, Albert Einstein ); The second argument of the strcpy function is copied into the first argument including the null terminator. Hence, copying Albert Einstein into the name array. If anything is already stored in the location referenced by the first argument, it is overwritten. Ex: char string1[10] = Hello, string2[10] = World ; cout << string1 << endl; Overwrites string1 with string2 cout << string2 << endl; strcpy(string1, string2); cout << string1 << endl; cout << string2 << endl; Code produces this output Hello World! World! World!

The strncat and strncpy Function Because the strcat and strcpy functions can potentially overwrite the bounds of an array, it is possible to write unsafe code. As an alternative, you should use the strncat and strncpy wherever possible. The strncat function works like strcat, except it takes a third argument specifying the maximum number of characters from the second string to append to the first. Ex: strncat(string1, string2, 10); Copies no more than 10 characters from string2 into string1.

Sample program shows an example of calculating the maximum number of characters that can be appended to an array. Ex: maxchars = 17 (8 + 1) maxchars = 8 int maxchars; char string1[17] = Welcome ; char string2[18] = to North Carolina ; maxchars = sizeof(string1) (strlen(string1) + 1); strcat(string1, string2, maxchar2); cout << string1 << endl; Accounts for null terminator

Calling strncpy is similar to calling strcpy, except you pass a third argument specifying he maximum number of characters from the second string to copy to the first. Ex: strncpy(string1, string2, 5); When executed, strncpy will copy no more than five characters from string2 to string1. If the number of characters is less than or equal to the length of string2, a null terminator is not appended to string1. If the specified number of characters is greater than the length of string2, then string 1 is padded with null terminators (up to the specified number of characters)

strncpy example: int maxchars; char string1[11]; char string2[ ] = I love C++ programming! ; maxchars = sizeof(string1-1); strncpy(string1, string2, maxchars); // Put the null terminator at the end. string1[10] = \0 ; cout << string1 << endl; The above statement adds the null terminator at the end of string1. This is done because maxchars was less than the length of string2, and strncpy did not automatically place a null terminator there.

The strstr Function The strstr function searches for a string inside of a string. The function s first argument is the string to be searched, and the second argument is the string to look for. If the function finds the second string inside the first, it returns the address of the occurrence of the second string within the first string. Otherwise it returns the address 0, or the NULL address. Ex char arr[ ] = Four score and seven years ago ; char *strptr; cout << arr << endl; strptr = strstr(arr, seven ); // search for seven cout << strptr << endl; Will output: seven years ago Will output: Four score and seven years ago In this code, strstr locates the string seven inside the string Four score and seven years ago. It returns the address of the first character in seven which will be stored in the pointer variable strptr.

// This program uses the strstr // function to search an array. #include <iostream> #include <cstring>// For strstr using namespace std; int main() { // Constants for array lengths const int NUM_PRODS = 5; const int LENGTH = 27; // String length // Number of products // Array of products char products[num_prods][length] = {"TV327 31-inch Television", "CD257 CD Player", "TA677 Answering Machine", "CS109 Car Stereo", "PC955 Personal Computer"}; char lookup[length]; char *strptr = NULL; int index; Sample Program // To hold user's input // To point to the found product // Loop counter return 0; } // Prompt the user for a product number. cout << "\tproduct Database\n\n"; cout << "Enter a product number to search for: "; cin.getline(lookup,length); // Search the array for a match substring for (index = 0; index < NUM_PRODS; index++) { strptr = strstr(products[index], lookup); if (strptr!= NULL) break; } // If a matching substring was found, // display the product info. if (strptr!= NULL) cout << products[index] << endl; else cout << "No matching product was found.\n";

String/Numeric Conversion Function The C++ library provides functions for converting a string representation of a number to a numeric data type and vice versa. These functions require the cstdlib header file to be included. The string 26792 isn t actually a number, but a series of ASCII codes representing the individual digits of the number. It uses six bytes of information including the null terminator and it is not possible to perform mathematical operations with it. Function atoi atol atof itoa String Conversion Functions Description Converts the C-string to an integer and return that value. Ex: num = atoi( 4569 ); Converts the C-string to a long integer and return that value. Ex: lnum = atol(500000 ); Converts the C-string to a double and returns that value. fnum = atof( 3.14159 ); Converts integer to C-string. (8 = octal, 10 = decimal, 16 = hexadecimal) itoa(value, string, base);

The atoi Function Ex: The atol Function Ex: The atof Function Ex: The itoa Function Ex: int num; num = atoi( 1000 ); long bignum; bignum = atol( 500000 ); double; num = atof( 12.67 ); char numarray[10] itoa(1200, numarray, 10); cout << numarray << endl;

The C++ string Class Standard C++ provides a special data type for storing and working with strings. The string class is an abstract data type. This means it is not a built-in, primitive data type line int or char. Instead, it is a programmer-defined data type that accompanies the C++ language. It provides many capabilities that make storing and working with strings easy and intuitive. The first step in using the string class is to #include the string header file. This accomplished with the following preprocessor directive: #include <string> Now you are ready to define a string object. Defining a string object is similar to defining a variable of a primitive type. Ex: string movietitle;

The C++ string Class You assign a string value to the movietitle object with the assignment operator, as movietitle = Wheels of Fury ;