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

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.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
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.
 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.
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays 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.
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.
5.1Introduction Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship with arrays and strings.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
Friday, January 05, 2007 A few weeks of developing and testing can save a whole afternoon in the library. -Anonymous.
C-Strings A C-string (also called a character string) is a sequence of contiguous characters in memory terminated by the NUL character '\0'. C-strings.
String What it is Why it’s useful library routines for handling strings how to input a string from the keyboard.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Arrays & Pointers.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
1 Chapter 10 Characters, Strings, and the string class.
Chapter 5 Arrays and Strings C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
Introduction to C programming
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
 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.
Chapter 8 Characters and Strings Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Characters, Strings, And The string Class Chapter 10.
Chapter 8: Character and String CMPD144: Programming 1.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
1 Chapter 5 - Pointers and Strings Outline 5.1Introduction 5.2Pointer Variable Declarations and Initialization 5.3Pointer Operators 5.4Calling Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 namespaces Program has identifiers in different scopes –Sometimes scopes overlap, lead to problems Namespace.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
 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. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
 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)
Strings, Pointers and Tools
1 Lecture 8 Pointers and Strings: Part 2 Section 5.4, ,
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
1 Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character Handling Library 8.4String Conversion.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
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.
C Characters and Strings
Fundamentals of Characters and Strings
Chapter 8 - Characters and Strings
Remark: Data Type of Array Name
Pointers and Pointer-Based Strings
String in C++.
Lecture 2 Arrays & Pointers May 17, 2004
C++ Programming Lecture 20 Strings
Lecture 2 Arrays & Pointers September 7, 2004
Presentation transcript:

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]

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

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

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

String Library Functions Useful for string manipulation #include 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 strstr(s1,s2)Searches first occurrence of s2 in s1, if found returns pointer otherwise returns NULL

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

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?

Output is: hello there

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 ?

strcmp(s1, s2) … bool password(); int main() { if ( password() ) cout << "Logged on.\n"; else cout << "Access denied.\n"; return 0; }

// 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) …

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

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

Write your own strLength(s) strCompare(s1, s2) strCopy(s1, s2); strConcatenate(s1, s2)

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

To Upper char mystring[80] = "i am a string"; int i=0; while ( mystring[i] ) {// mystring[i] - ’a’ + ’A’ char upper = mystring[i] - ( ); cout << upper; i++; }

#include 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

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

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

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

Madrid c ? Islamabad m Example

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

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

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

// 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

Reference Dietel & Dietel

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

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

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

Fundamentals of Strings cin.getline –Copies input into specified array until either One less than the size is reached The delimiter character is input –Example char sentence[ 80 ]; cin.getline( sentence, 80, '\n' );

String Manipulation Functions of the String-handling Library String handling library 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)

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.

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.