+ All Categories
Home > Documents > Introduction to Programming Lecture 8. String Handling Character is the building block of strings. ...

Introduction to Programming Lecture 8. String Handling Character is the building block of strings. ...

Date post: 14-Dec-2015
Category:
Upload: dwain-eaton
View: 228 times
Download: 2 times
Share this document with a friend
86
Introduction to Programming Lecture 8
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 Initializationchar 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

\n New Line

\t Tab Character

\0 Null 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 ArrayInitializing 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 arrayschar 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 ArraysDisplaying name on screen using loop

for ( i = 0 ; i < 100 ; i ++ ){

cout << name [ i ] ;}

Comparing Two arraysArray 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” ;

elsecout << “ 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<iostream.h>main ( ){

int i ;char c ;for( i = 0; i < 256 ; i ++ ){

c = i ;cout << i << “\t” << c <<endl ;

}}

Header File

ctype.h#include<ctype.h>

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 ( ) ;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 StringsA string containing a single character

takes up 2 bytes of storage.

Character Strings

Character Strings

Characters vs. 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/OString 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

getlinegetline

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: Example 3: getlinegetline

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.

This is a test.

END OF OUTPUT

Example 4: Example 4: getline getline ExampleExample

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 <cstring>String Copy Function in <cstring>

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:

name2:

strcpy(name2,"999999999999999");

strcpy(name2,name1);

CC hh aa nn TT aa ii MM aa nn \0\0 ?? ?? ??

CC hh aa nn TT aa ii MM aa nn \0\0 99 99 \0\0

99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 \0\0

strcpy in <cstring>strcpy in <cstring>

#include <iostream>#include <cstring>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 <cstring>String Length Check Function in <cstring>

// string prototype, already included in string.h

//returns length of string(not counting'\0‘)

//you don't need to include it in your program

intint strlen( strlen(constconst charchar[]);[]);

intint string_length = strlen("abcde"); string_length = strlen("abcde");

//string_length is set to 5.//string_length is set to 5.

String Length Check Function ExampleString Length Check Function Example

#include <iostream.h> int main(){

char string_1[5] = "ABCD", string_2[10]="123456789"; 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 = ABCDString 2 = 123456789After copying, string 1 = 1234

String ComparisonString 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

= 0 if s1 == s2 (i.e. strcmp returns false) = 0 if s1 == s2 (i.e. strcmp returns false)

> 0 if s1 > s2 > 0 if s1 > s2

*/*/

Some Common ErrorsSome 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 ErrorsSome 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

60000

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

Exampleint *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

Examplemain ( ){

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 ;

Examplemain ( ){

int x = 10 , y = 20 , * yptr , * xptr ;yptr = &y ;xptr = &x ;swap ( yptr , xptr ) ;

}

Exampleswap ( int *yptr , int *xptr ){

… … …}

const

int *const myptr = &x ;

myptr is a constant pointer to an integer

const

const int x = 10 ;

constconst int *myptr = &x ;

myptr is a pointer to a constant integer

Arrayint a [ 10 ] ;

11

22

33

44

55

66

77

88

99

1010

aStarting 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

11 22 33 44 1100

77 99 1111

1144

1100

1177

2255

3399

4455

5588

Placed sequentially in the memory

1st row 1st col

2nd row1st col

[0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [0] [1] [2] [3] [4]

3rd row1st 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<iostream.h>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 3char 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

h e l l ot e s t \0 \0

Initialization

char *myArray [ ] = { “test ” , “ hello ” } ;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 << pEmployee ->title;

Pointers to a data structurePointers to a data structure

Where are we

Conclude last lectureConclude last lecture Pointers to PointersPointers to Pointers Pointers with Multidimensional ArraysPointers 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,000 No tax5001 – >10,000 5% Income Tax10,001 – >20,000 10% Income Tax20,001 and more 15% Income tax

ExampleNet salary = Rs 10,000Tax = 5%Amount Deducted = 5% of 10,000

= 500Net amount after deduction = 10,000 - 500

= 9,500

Net salary = Rs 10,001Tax = 10%Amount Deducted = 10% of 10,001

= 1,000.1Net amount after deduction = 10,001 - 1,000.1

= 9,000.9

Storage Requirement

One- dim arrays of integer

lucky = 0 lucky = 1

00

00

00

00

00

00

00

Storage of salary11 5,0005,000 5,0005,000

22 10,00010,000 9,5009,500

33

44

55

66

77

88

99

1010

GrowSalary

Net Salary After Deduction

No ofEmp.

Interface Requirements

Distribution of the Program

• Input• Salary calculation• Identification of the unlucky individuals• Output

Detail DesignFunctions in the program

getInput calculateSalarylocateUnluckyIndividualdisplayOutput

Code#include<iostream.h>

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

}

CodegetInput ( int sal [ ] [2] , int numEmps ){

for ( i = 0 ; i < numEmps ; i ++ )cin >> sal [ i ] [ 0 ] ;

}


Recommended