Introduction to Programming Lecture 8. String Handling  Character is the building block of strings.  Characters are represented inside the computer.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
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 20 Arrays and Strings
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.
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
Chapter 10.
COMP102 – Programming Fundamentals I LA2B (Mon 5-7pm) LA2E (Fri 3-5pm) LA2F (Fri 5-7pm) TA: Jackie Lo.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
Arrays Chapter 6.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Programming Strings. COMP102 Prog. Fundamentals: Strings / Slide 2 Character Strings l A sequence of characters is often referred to as a character “string”.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Chapter 8 Arrays and Strings
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
1 Chapter 10 Characters, Strings, and the string class.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
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.
Chapter 8 Arrays and Strings
Chapter 10. Characters, Strings and the string class Csc 125 Introduction to C++ Fall 2005.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
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.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 10: Characters, C- Strings, and More About.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Introduction to C++ Part II Version 1.3. Topics C++ Functions -- passing by value in C++ -- passing by reference in C++ -- passing by address in C++ C++
COIT29222-Structured Programming Lecture Week 08  Reading: Textbook (4 th Ed.), Chapter 4 Textbook (6 th Ed.), Chapter 7 Study Guide Book 2, Module 11.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
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.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter Characters, Strings, and the string class 10.
Strings, Slide Fundamental Programming Strings.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Suyash Bhardwaj Dept. of Computer Science & Engineering Faculty of Engineering & Technology Gurukul Kangri University, Haridwar l1l1 UNIT 1 String Processing.
Introduction to Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
C Characters and Strings
Programming Fundamental
Characters, C-Strings, and More About the string Class
Introduction to Programming
Arrays in C.
Chapter 8 - Characters and Strings
Standard Version of Starting Out with C++, 4th Edition
C++ Pointers and Strings
Standard Version of Starting Out with C++, 4th Edition
Strings Skill Area 313 Part C
C++ Pointers and Strings
Presentation transcript:

Introduction to Programming Lecture 8

String Handling  Character is the building block of strings.  Characters are represented inside the computer as numbers, e.g. ASCII  You can write a program to print ASCII table.

String Initialization char name [ 20 ] ; name [ 0 ] = ‘G’ ; name [ 1 ] = ‘o’ ; name [ 2 ] = ‘o’ ; name [ 3 ] = ‘d’ ; name [ 4 ] = ‘\0’ ;

String Initialization char name [ 20 ] = “RPI” ; Array must be one character space larger than the number of printable character which are to be stored.

In C we have Used \nNew Line \tTab Character \0Null Character All C strings are terminated by Null character

Character Array in Memory char name [ 100 ] ; cout << “ Please enter your name ” ; cin >> name ;

Initializing an Array Initializing array of integers int c [ 10 ] = { 1,2,3,4,5,6,7,8,9,10 } ; int c [ ] = { 1,2,3,4,5,6,7,8,9,10 } ; For character arrays char name [ 100 ] = { ‘a’,b’,’c’,’0’,’1’ } ; char name [ 100 ] = “abc01“ ; char name [ ] = “Hello World“ ;

Character Arrays To read name from keyboard and display it on screen char name [ 100 ] ; cout << “ Please enter you name” ; cin >> name ; cout << name ;

Character Arrays Displaying name on screen using loop for ( i = 0 ; i < 100 ; i ++ ) { cout << name [ i ] ; }

Comparing Two arrays Array size should be equal int equal = 0 ; int num1 [ 100 ], num2 [ 100 ] ; for ( i = 0 ; i < 100 ; i ++ ) { if ( num1 [ i ] != num2 [ i ] ) { equal = 1 ; break ; } } if ( equal ==1 ) cout << “ The arrays are not equal” ; else cout << “ The arrays are equal” ; Condition :

Comparing Two Arrays AZMAT HAMEED Azmat Hameed

Exercise Self Study: cin.get(MAX), cin.get(str, MAX,‘$’) Input your name and display it in reverse order Determine the length of character array

Example #include main ( ) { int i ; char c ; for( i = 0; i < 256 ; i ++ ) { c = i ; cout << i << “\t” << c <<endl ; }

Header File ctype.h #include

ctype Functions int isdigit ( int c ) int isalpha ( int c ) int isalnum ( int c ) int isxdigit ( int c ) int islower ( int c ) int isupper ( int c ) int tolower ( int c ) int toupper ( int c ) int isspace ( int c ) int iscntrl ( int c ) int ispunct ( int c ) int isprint ( int c ) int isgraph ( int c )

cout << “Please enter a character string then press enter”; while ( ( c = getchar ( ) ) != ‘\n’ ) { if ( islower ( c ) ) lc ++ ; else if ( isupper ( c ) ) uc ++ ; else if (isdigit ( c ) ) dig ++; else if ( isspace ( c ) ) ws ++ ; else if ( ispunct ( c ) ) pun ++ ; else oth ++ ; } getchar ( ) ;

Character Strings  A sequence of characters is often referred to as a character “ string ”.  A string is stored in an array of type char ending with the null character '\0 '.

Character Strings  A string containing a single character takes up 2 bytes of storage.

Character Strings

Characters vs. Strings

 A string constant is a sequence of characters enclosed in double quotes.  For example, the character string: char s1[2]= " a "; //Takes two bytes of storage.  On the other hand, the character, in single quotes: char s2= `a `; //Takes only one byte of storage.

Example char message1[12] = "Hello world"; cout << message1 << endl; message1:

char message2[12]; cin >> message2; // type "Hello" as input message2:

Example 2: String I/O String can be input using the extraction operator >>, but one or more white spaces indicates the end of an input string. char A_string[80]; cout << "Enter some words in a string:\n"; cin >> A_string; cout << A_string << “\nEND OF OUTPUT\n"; Output: Enter some words in a string: This is a test. This END OF OUTPUT

getline The function getline can be used to read an entire line of input into a string variable. The getline function has three parameters: The first specifies the area into which the string is to be read. The second specifies the maximum number of characters, including the string delimiter. The third specifies an optional terminating character. If not included, getline stops at ‘\n’.

Example 3: getline char A_string[80]; cout << "Enter some words in a string:\n"; //80 is the size of A_string cin.getline(A_string, 80); cout << A_string << “\nEND OF OUTPUT\n"; Output: Enter some words in a string: This is a test. END OF OUTPUT

Example 4: getline Example char A_string[5], E_string[80]; cout << "Enter some words in a string:\n"; cin >> A_string; cin.getline (E_string, 9) ; cout << A_string << "#" << E_string << “\nEND OF OUTPUT\n"; Output: Enter some words in a string: This is a test. This# is a te END OF OUTPUT

String Copy Function in String Copy Function in void strcpy(char dest[], const char src[]); // copies string src into string dest example: char name1[16], name2[16]; strcpy(name1,"Chan Tai Man"); name1: name2: strcpy(name2," "); strcpy(name2,name1); ChanTaiMan\0??? ChanTaiMan\099\ \0

strcpy in strcpy in #include using namespace std; int main (){ char string_1[6] = "Short"; char string_2[17] = "Have a Nice Day"; char string_3[6] = "Other"; strcpy(string_1, string_2); return 0; }

String Length Check Function in String Length Check Function in // string prototype, already included in string.h //returns length of string(not counting'\0‘) //you don't need to include it in your program int strlen(const char[]); int string_length = strlen("abcde"); //string_length is set to 5.

String Length Check Function Example #include int main(){ char string_1[5] = "ABCD", string_2[10]=" "; cout << "String 1 = " << string_1 << endl; cout << "String 2 = " << string_2 << endl; strcpy(string_1,string_2,strlen(string_1)); cout << "After copying, string 1 = " << string_1<<endl; return 0; } //output: String 1 = ABCD String 2 = After copying, string 1 = 1234

String Comparison int strcmp(char s1[], char s2[]); /*compares strings s1 and s2, returns /*compares strings s1 and s2, returns < 0 if s1 < s2 = 0 if s1 == s2 (i.e. strcmp returns false) > 0 if s1 > s2 */ */

Some Common Errors It is illegal to assign a value to a string variable (except at declaration). char A_string[10]; A_string = "Hello"; // illegal assignment Should use instead strcpy (A_string, "Hello");

Some Common Errors Some Common Errors The operator == doesn't test two strings for equality. if (string1 == string2) //wrong cout << "Yes!"; // illegal comparison Should use instead if (!strcmp(string1,string2)) cout << "Yes they are same!"; //note that strcmp returns 0 (false) if //the two strings are the same.

Pointers A variable that holds address value is called Pointer variable

Pointers 10 x Location Address of x

Declaring Pointer to Integer int *myptr ; myptr is pointer to an integer

Declaring Pointers double *x ; char *c ;

A string is a null terminated array of characters. – null terminated means there is a character at the end of the the array that has the value 0 (null). char *msg = “RPI”; 'R' msg zero (null) 'P''I'0 String Initialization

Example int *ptr ; int x ; x = 10 ; ptr = &x ;

Dereferencing Operator * *ptr is read as “The value of what ever ptr points to”

z = *ptr * 2 ;

Initializing Pointers ptr = &var ; ptr = 0 ; ptr = NULL ; 0 and NULL points to nothing

Example main ( ) { int numEmp ; …. funct ( &numEmp ) ; …. } void funct ( int *numEmp ) { cin >> *numEmp ; }

Declaring pointers int *ptr1, *ptr2, *ptr3 ;

Declaring pointers int *ptr, x ;

Declaring pointers int *ptr, x, a [ 10 ] ;

Swapping

Swap temp = x ; x = y ; y = temp ;

Example main ( ) { int x = 10, y = 20, * yptr, * xptr ; yptr = &y ; xptr = &x ; swap ( yptr, xptr ) ; }

Example swap ( int *yptr, int *xptr ) { … … … }

const int *const myptr = &x ; myptr is a constant pointer to an integer

const const int x = 10 ;

const const int *myptr = &x ; myptr is a pointer to a constant integer

Array int a [ 10 ] ; a Starting Address of Array

Example 1 char myName [ ] = “Aqdus” ; char *myNamePtr = “Aqdus” ; Difference ? Constant Vs Variable Pointer

Multi-dimensional Arrays char multi [ 5 ] [ 10 ] ; where does multi point to in two dimension array? multi points to beginning of the array Lets take a look how multi-dimensional arrays are stored in the memory

Multi-dimensional Array in Memory Placed sequentially in the memory 1st row 1st col 2nd row 1st col [0] [1] [2] [3] [4] 3rd row 1st col What should happen if we increment multi ? What happens in single dimensional array ? It is important to know, what does multi point to ? and how to dereference it.

Dereferencing array element multi [ 2 ] [ 3 ] We derefer arrays by subscripts We derefer pointers by *

*multi ? It still holds the address: Address of the first row

Example 2 #include main ( ) { int multi [ 5 ] [ 10 ] ; cout << multi << endl ; cout << *multi ; cout << **multi ; } // *multi is still a pointer // We derefer the first element of the first row

Example 3 char multi [ 2 ] [ 2 ] ; multi[0][0]=‘a’; multi[0][1]=‘b’; multi[1][0]=‘c’; multi[1][1]=‘d’; cout << multi << endl; cout <<*multi<<endl; cout <<**multi;

multi + 3 *( multi + 3 ) *( multi + 3 ) + 3 *(*( multi + 3 ) + 3 ) // go to the fourth row // Beginning of the fourth row // address of fourth row, fourth column // value at fourth row, fourth column Alternative way of array manipulation

main ( ) { int multi [ 5 ] [ 6 ] ; int row, col ; int *ptr ; ptr = *multi ; for ( row = 0 ; row < 5 ; row ++ ) { for ( col = 0 ; col < 10 ; col ++ ) { multi [ row ] [ col ] = row * col ; } Example 4

Example 5 for ( row = 0 ; row < 5 ; row ++ ) { for ( col = 0 ; col < 10 ; col ++) { cout << *( ptr ++ ) << “ ”; } cout << endl ; } // Straight line storage // That's why when we pass multi dimensional array to a function we need to give the dimensions. // It needs to know the number of columns in the array // It needs to know where a row ends and the other start.

Pointers to Pointers Double dereferencing Pointer itself can be considered as an array

Array of Pointers Calculate the average age of the class : Store Names Memory allocation according to need: new The length of the string at initialization time of the character array, defines the size of the array Multidimensional character arrays: memory allocation = row X columns Equal space for all: No variable space Solution ?

Array of Pointers char *myArray [ 10 ] ; myArray is an array of 10 pointer to character

0xefffbab00xefffa0d0 hellotest\0 Initialization char *myArray [ ] = { “test ”, “ hello ” } ; Variable storage of strings: Hold the starting addresses of each strings: Arrays of pointers:

Storing Pointers in Array of Pointers int *p1, *p2, *p3 ; int *b [ 3 ] ; b [ 0 ] = p1 ; b [ 1 ] = p2 ; b [ 2 ] = p3 ;

Command Line Arguments argc argv ‘argc’ stands for a count of the number of arguments ‘argv’ stands for a vector of arguments

Example 4 main ( int argc, char **argv ) { cout << argc << "\n“ << *argv ; } Your program knows its name now

-> struct Employee { char title [50]; int year; }; Employee aEmployee; Employee * pEmployee; pEmployee = & aEmployee; cout title; Pointers to a data structure

Where are we Conclude last lecture Conclude last lecture Pointers to Pointers Pointers to Pointers Pointers with Multidimensional Arrays Pointers with Multidimensional Arrays Advantages of memory allocation in C++ Advantages of memory allocation in C++ Uses of memory allocation Uses of memory allocation

Practical Problem Problem statement Given tax brackets and given employee gross salaries, determine those employees who actually get less take home salary than others with lower initial income

Rule for tax deduction 0 –> 5,000No tax 5001 – >10,0005% Income Tax 10,001 – >20,00010% Income Tax 20,001 and more 15% Income tax

Example Net salary = Rs 10,000 Tax = 5% Amount Deducted = 5% of 10,000 = 500 Net amount after deduction = 10, = 9,500 Net salary = Rs 10,001 Tax = 10% Amount Deducted = 10% of 10,001 = 1,000.1 Net amount after deduction = 10, ,000.1 = 9,000.9

Storage Requirement One- dim arrays of integer lucky = 0 lucky =

Storage of salary 15,0005, ,0009, Grow Salary Net Salary After Deduction No of Emp.

Interface Requirements

Distribution of the Program Input Salary calculation Identification of the unlucky individuals Output

Detail Design Functions in the program getInput calculateSalary locateUnluckyIndividual displayOutput

Code #include void getinput ( int [ ] [ 2 ], int ) ; main ( ) { const int arraySize = 100 ; int sal [ arraySize ] [ 2 ] ; int lucky [ arraySize ] = { 0 } ; int numEmps ; cout << “Enter the number of employess “ ; cin >> numEmps ; getInput ( sal, numEmps ) ; }

Code getInput ( int sal [ ] [2], int numEmps ) { for ( i = 0 ; i < numEmps ; i ++ ) cin >> sal [ i ] [ 0 ] ; }

Tax Prog Detailed Code calculateSalary ( int sal [ ] [ 2 ], int lucky [ ], int numEmps ) { for ( i = 0 ; i < numEmps ; i ++ ) { // netSalary = grossSalary – tax if ( sal [ i ] [ 0 ] <= 5000 ) { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] ; }

Code else { if ( sal [ i ] [ 0 ] <= ) { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] *sal [ i ] [ 0 ] ; }

Code else { if ( sal [ i ] [ 0 ] <= ) { sal [ I ] [ 1 ] = sal [ I ] [ 0 ] * sal [ I ] [ 0 ] ; }

Code else { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] * sal [ i ] [ 0 ] ; }

if ( sal [ i ] [ 0 ] >= 0 && sal [ i ] [ 0 ] <= 5000 ) { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] ; } if ( sal [ i ] [ 0 ] > 5000 && sal [ i ] [ 0 ] < ) { sal [ i ] [ 1 ] = sal [ i ] [ 0 ] * sal [ i ] [ 0 ] ; }... … …

if ( grossSalary > sal [ i ] [ 0 ] && netSalary < sal [ i ] [ 1 ] ) This logic will fail

Code void locateUnluckyIndividual ( int sal [ ] [ 2 ], int lucky [ ], int numEmps ) { int i, j ; int grossSalary, netSalary ; for ( i = 0 ; i < numEmp ; i ++ ) { grossSalary = sal [ i ] [ 0 ] ; netSalary = sal [ i ] [ 1 ] ; for ( j = 0 ; j < numEmp ; j ++ ) { if ( grossSalary > sal [ j ] [ 0 ] && netSalary < sal [ j ] [ 1 ] ) { lucky [ i ] = 1 ; }

Code void displayOutput ( int sal [ ] [ 2 ], int lucky [ ], int numEmps ) { for ( i = 0 ; i < numEmp ; i ++ ) { if ( lucky [ i ] == 1 ) { cout<< “Employee No.” << i+1 << “ is unlucky, Gross Salary = ” << sal [ i ] [ 0 ] << “ Net Salary = ” << sal [ i ] [ 1 ] << “\n” ; }