CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

34
CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    218
  • download

    3

Transcript of CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Page 1: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

CS 192

Lecture 11

Winter 2003

December 29-30, 2003

Dr. Shafay Shamail

Page 2: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Strings• A collection of items of same type in contiguous memory

• One-dimensional array of type char e.g. ”hello”• A string is in double quotes and is called literal string constant

• A string is terminated by the null character: ‘\0’ (a zero)

• Compiler automatically appends it at the end of string; signifies end of string for the compiler

• char str[6] = “hello”;• str[5] is what?

• char a1[]=“abc”;• char a2[]={‘a’, ‘b’, ‘c’};• char a3[]={‘a’, ‘b’, ‘c’, ‘\0’};• cout<<a1; cout<<a2; cout<<a3;• Is a2[] a string?

• char b[4]=“hi”; b[3] set to zero (null) as is b[2]

Page 3: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Reading Strings from Keyboard• The easiest way to read a string entered from

the keyboard is to make a character array

int main()

{

char str[80];

cout << "Enter a string: ";

cin >> str; // read string from keyboard

cout << "Here is your string: ";

cout << str<<"\n";

return 0;

}

Page 4: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Reading Strings from Keyboard• There is a problem with previous program, if the string has

whitespace characters (space, tab, newline)

• Use gets() to read a string from the keyboard. #include <stdio.h>

int main()

{

char str[80];

cout << "Enter a string: ";

cout.flush();

gets(str); // read a string from the keyboard

cout << "Here is your string: ";

cout << str<<“\n”;

return 0;

}

Page 5: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

/*

The gets function reads a line,

which consists of all characters up to and including the first newline character ('\n').

gets then replaces the newline character with a null character ('\0') before returning the line.

*/

gets() Library Function

Page 6: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

String Library FunctionsUseful for string manipulation

#include <string.h>

l=strlen(s) Returns string length excluding NULL

strcat(s1,s2) Concatenates s2 to s1

strcpy(s1,s2) Copies s2 to s1

strncpy(s1,s2,n) Copies n characters from s2 to s1

strcmp(s1,s2) Returns 0 if equal, -ve if s1<s2, +ve if s1>s2

strstr(s1,s2) Searches first occurrence of s2 in s1, if found returns pointer otherwise returns NULL

Page 7: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

String Library Functions

==========================

strcpy(s1, s2)

Copies until \0 is moved. Contents of s1 overwritten

s1 should have enough space. The value of s1 is returned

==========================int main()

{ char str[80];

strcpy(str, "hello");

cout << str;

return 0;

} // Output is: hello

Page 8: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

String Library Functions

==========================

strcat(s1, s2)

Appends s2 to the end of s1 and returns s1. s2 is unchanged

==========================

int main()

{ char s1[20], s2[10];

strcpy(s1, "hello");

strcpy(s2, " there");

strcat(s1, s2);

cout << s1<<“\n”;

return 0;

} //output?

Page 9: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Output is:hello there

Page 10: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

String Library Functions==========================

strmp(s1, s2)

==========================

• compares two strings lexicographically• returns 0 if they are equal (dictionary order)• returns a +ve number if s1 is greater than s2• returns a -ve number if s1 is less than s2

strcmp(“Zoo”, “ape”);

ASCII code has uppercase before lowercase

strcmp(“Zoo”, “zoo”); // Output ?

Page 11: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

strcmp(s1, s2) …

bool password();

int main(){

if ( password() ) cout << "Logged on.\n";

else cout << "Access denied.\n"; return 0;

}

Page 12: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

// Return true if password accepted; false otherwise.bool password()

{

char s[80];

cout << "Enter password: ";

gets(s);

if ( strcmp(s, "password") ) // strings differ

{

cout << "Invalid password.\n";

return false;

}

// strings compared the same

return true;

}

strcmp(s1, s2) …

Page 13: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

int main()

{

char s[80];

for(;;)

{

cout << "Enter a string: ";

cout.flush();

gets(s);

if( !strcmp("quit", s) )

break;

}

return 0;

}

strcmp(s1, s2) …

int main()

{

char s[80];

do

{ cout << "Enter a string:"; gets(s); } while(strcmp("quit",s));

//other than 0 is true

return 0;

}

Page 14: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

String Library Functions

==========================strlen(s)

returns the length of s

==========================int main()

{

char str[80];

cout << "Enter a string: ";

gets(str);

cout << "Length is: " << strlen(str) <<"\n";

return 0;

}

//what is the output if we enter: this is cs192

Page 15: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Write your own

• strLength(s)

• strCompare(s1, s2)

• strCopy(s1, s2);

• strConcatenate(s1, s2)

Page 16: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

String/Numeric Conversion n=atoi(s) Converts s to integer

ln=atol(s) Converts s to a long integer

fn=atof(s) Converts s to a float

itoa(v,s,b) Converts v integer of base b to a string s

Page 17: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

To Upper

char mystring[80] = "i am a string";int i=0;

while ( mystring[i] ){ // mystring[i] - ’a’ + ’A’

char upper = mystring[i] - (97 - 65);cout << upper;i++;

}

Page 18: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

#include <string.h> void main(){ char str[80]; int i;

strcpy(str, "this is a test");

for(i=0; str[i]; i++)str[i] = toupper(str[i]);

cout << str << endl;

}

Using Null Terminator

Page 19: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

• Test condition of the for loop is simply the array indexed by i

• Loop runs until it encounters the null terminator.

==================================

toupper() tolower() isalpha()

isdigit() isspace() ispunct()

Using Null Terminator

Page 20: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

• The following declares an array of 30 strings• Each having a maximum length of 80 characters

char str_array[30][80];

• In order to access an individual string, specify only the left index.

Arrays of Strings

Page 21: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

int main()

{

char city[80] = "Islamabad";

char places[4][80] = {"Lahore", "Hanoi", "Karachi", "Madrid"};

cout << places[3] << '\n';

cout << places[2][4] << '\n';

cout << places[1][6] << '\n';

cout << city << '\n';

cout << city[4] << '\n';

return 0;

}

Example

Page 22: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Madrid

c

?

Islamabad

m

Example

Page 23: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

int main() {

int t, i; char text[100][80];

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

cout << t << ": ";cout.flush();

gets ( text[t] ); if ( !text[t][0] )

break; // quit on blank line } // redisplay the strings for(i=0; i<t; i++) cout << text[i] << '\n'; return 0; }

Arrays of Strings

Page 24: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

const int EMPLOYEES = 10; // this array holds employee names

char name[EMPLOYEES][80]; // their phone numbers

char phone[EMPLOYEES][20]; // hours worked per week

float hours[EMPLOYEES]; // wage

float wage[EMPLOYEES];

Example using String Arrays

Page 25: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

void enter() // Enter information.{ int i; for(i=0; i<EMPLOYEES; i++) {

cout << "Enter last name: "; cin >> name[i]; cout << "Enter phone number: "; cin >> phone[i]; cout << "Enter number of hours worked: "; cin >> hours[i]; cout << "Enter wage: "; cin >> wage[i];

}}

Example using String Arrays

Page 26: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

// Display report.

void report()

{

int i;

for(i=0; i<EMPLOYEES; i++)

{

cout << name[i] << ' ' << phone[i] << '\n';

cout << "Pay for the week: " << wage[i] * hours[i];

cout << '\n';

}

} //employee example

Example using String Arrays

Page 27: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Reference

Dietel & Dietel

Page 28: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Fundamentals of Strings

Series of characters treated as one unit• Can include letters, digits, special characters +, -, * ...• String literal (string constants)

– Enclosed in double quotes, for example:"I like C++"

• Array of characters, ends with null character '\0'• Strings are constant pointers (like arrays)

– Value of string is the address of its first character

Page 29: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Fundamentals of Strings

• String assignment– Character array:

char color[] = "blue";

• Creates 5 element char array, color, (last element is '\0')

– variable of type char *char *colorPtr = "blue";

• Creates a pointer to string “blue”, colorPtr, and stores it somewhere in memory

Page 30: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Fundamentals of Strings• Reading strings

– Assign input to character array word[ 20 ]cin >> word

• Reads characters until whitespace or EOF• String could exceed array size

cin >> setw( 20 ) >> word;

• Reads 19 characters (space reserved for '\0')

• cin.getline– Reads a line of text– Using cin.getline

cin.getline( array, size, delimiter character);

Page 31: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

Fundamentals of Strings

• cin.getline– Copies input into specified array until either

• One less than the size is reached

• The delimiter character is input

– Examplechar sentence[ 80 ];

cin.getline( sentence, 80, '\n' );

Page 32: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

String Manipulation Functions of the String-handling Library

• String handling library <cstring> provides functions to– Manipulate strings

– Compare strings

– Search strings

– Tokenize strings (separate them into logical pieces)

• ASCII character code– Strings are compared using their character codes

– Easy to make comparisons (greater than, less than, equal to)

• Tokenizing – Breaking strings into tokens, separated by user-specified characters

– Tokens are usually logical units, such as words (separated by spaces)– "This is my string" has 4 word tokens (separated by spaces)

Page 33: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

String Manipulation Functions of the String-handling Library

char *strcpy

( char *s1, const char *s2 );

Copies the string s2 into the character

array s1. The value of s1 is returned.

char *strncpy

( char *s1, const char *s2, size_t n );

Copies at most n characters of the string s2 into the character array s1. The value of s1 is returned.

char *strcat

( char *s1, const char *s2 );

Appends the string s2 to the string s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned.

char *strncat

( char *s1, const char *s2, size_t n );

Appends at most n characters of string s2 to string s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned.

int strcmp

( const char *s1, const char *s2 );

Compares the string s1 with the string s2. The function returns a value of zero, less than zero or greater than zero if s1 is equal to, less than or greater than s2, respectively.

Page 34: CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.

String Manipulation Functions of the String-handling Library

int strncmp

( const char *s1, const char *s2, size_t n );

Compares up to n characters of the string s1 with the string s2. The function returns zero, less than zero or greater than zero if s1 is equal to, less than or greater than s2, respectively.

char *strtok

( char *s1, const char *s2 );

A sequence of calls to strtok breaks string s1 into “tokens”—logical pieces such as words in a line of text—delimited by characters contained in string s2. The first call contains s1 as the first argument, and subsequent calls to continue tokenizing the same string contain NULL as the first argument. A pointer to the current to ken is returned by each call. If there are no more tokens when the function is called, NULL is returned.

size_t strlen

( const char *s );

Determines the length of string s. The number of characters preceding the terminating null character is returned.