Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.

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

EC-111 Algorithms & Computing Lecture #11 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
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.
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.
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.
Chapter 10.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
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.
Character I/O. COMP104 Character I/O Slide 2 Data Type: char * Constant declaration const char star = '*'; * Variable declaration char resp; * Variable.
Characters. COMP104 Lecture 21 / Slide 2 Data Type: char * Constant declaration const char star = '*'; * Variable declaration char resp; * Variable assignment.
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.
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
1 Array, Pointer and Reference ( I ) Ying Wu Electrical Engineering and Computer Science Northwestern University EECS 230 Lectures.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
String What it is Why it’s useful library routines for handling strings how to input a string from the keyboard.
Computer Science 1620 Strings. Programs are often called upon to store and manipulate text word processors chat databases webpages etc.
In Addition... To the string class from the standard library accessed by #include C++ also has another library of string functions for C strings that can.
Chapter 8 Strings and Vectors (8.1 and 8.2). An Array of characters Defined as: char firstName[20]; char firstName[] = {‘T’, ‘i’, ‘m’}; // an array of.
Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
 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
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
Array, Pointer and Reference ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
CSC 270 – Survey of Programming Languages
CS 1430: Programming in C++ 1. Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
Chapter 15 Strings as Character Arrays
Chapter 9 Strings. Learning Objectives An Array Type for Strings – C-Strings Character Manipulation Tools – Character I/O – get, put member functions.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Strings, Pointers and Tools
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT9: Pointer I CS2311 Computer Programming.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
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.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
A Sample Program #include using namespace std; int main(void) { cout
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.
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Chapter 1.2 Introduction to C++ Programming
Fundamentals of Characters and Strings
String in C++.
String What it is Why it’s useful
Chapter 9 Strings Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
C++ Programming Lecture 20 Strings
CS31 Discussion 1H Fall18: week 6
Presentation transcript:

Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming

Outline 2 Characters Declaration and Initialization ASCII Input and Output Strings Declaration and Initialization Copy and compare Input and output

Syntax Summary 3 Keywords char Punctuators [],’ Constant ‘\0’, ‘\n’

Character data type 4 Written between single quotes. Examples 'A', 'b', '*' In C++ language, a char type is represented by an integer. Therefore, a character can also be treated as an integer

Character type examples 5 cout << 'a'; /* a is printed */ cout << (int)'a'; /* 97 is printed */ cout << (char)97; /* a is printed */

ASCII Table 6 ASCII value of '7' is 55 but not 7!

char features 7 AB...Z ab z 'a' + 1 has the value of 'b', 'b' + 1 has the value of 'c',... test if character c is lower-case letter: if ('a' <= c && c <= 'z')... same as: if (97 <=c && c <= 122)... If the variable c has the value of a lowercase letter, then the expression c + ('A' – ‘a’) /* same as c + (65 -97)*/ has the value of the corresponding uppercase letter

Example 8 #include using namespace std; void main(){ char c1='D', c2='e', c3,c4; c3=c1+'a'-'A'; //convert to lowercase c4=c2+'A'-'a'; //convert to uppercase cout<< “c3=“ << c3 << “, c4=“ << c4 << endl; //c3=d, c4=E }

Reading a characters 9 char c1,c2; cin >> c1; When cin >> c1 is reached, the program will ask the user for input. Suppose the character 'A' is input, c1 will evaluate to 65 (which is the ASCII code of 'A'). As a result, 65 will be assigned to the character c1. Therefore, c1 holds the character 'A'

Some facts about keyboard Input 10 Suppose >> is called to read a character. What if the user input more than 1 characters in a single line? Answer: The extra character will be stored in a buffer (certain memory location). The character will be retrieved later when << is called to read more characters.

Some facts about keyboard Input 11 c1c2c3Input buffer (user input “ cs2311”) cin >> c1;‘C’ cin >> c2;‘C’‘S’ cin >> c3;‘C’‘S’‘2’ char c1,c2,c3; cin >> c1; //enter the string "CS2311" cin >> c2; //get the character 'S' from buffer cin >> c3; //get the character '2' from buffer

Printing a character 12 char c1='A',c2='B'; cout << c1; cout.put(c1);

Example 13 Write a program which reads a character from the user and output the character type. The program should distinguish between the following types of characters An upper case character ( 'A'-'Z' ) A lower case character ( 'a'-'z' ) A digit ( '0'-'9' ) Special character (e.g. ' #', '$', etc.)

Answer 14 #include using namespace std; void main(){ char c; cin >> c; if ( ) cout << "An upper case character\n"; else if ( ) cout << "A lower case character\n"; else if ( ) cout << "A digit\n"; else cout << "Special character\n"; }

Answer 15 #include using namespace std; void main(){ char c; cin >> c; if (c>='A' && c<='Z') cout << "An upper case character\n"; else if (c>='a' && c<='z') cout << "A lower case character\n"; else if (c>='0' && c<='9') cout << "A digit\n"; else cout << "Special character\n"; }

Strings 16

cstring vs string object 17 In C++, there are two types of strings cstring: inherited from the C language string: class defined in library

String : cstring 18 A cstring is a char array, which is terminated by the end-of- string sentinel (or null character) '\0'. A character of array of size n may store a string with maximum length of n-1 Consider the definition char str[20]="Hello World"; HelloWorld\0 This character array may store a string with maximum length of 19

Rule of Safety 19 Declare a string with one more character than needed E.g. char studentID[9];// char HKID[11];//a123456(7)

cstring: Declaration and Initialization 20 String variable can be declared in one of two ways Without initialization char identifier[required size+1] E.g. char name[12];// name with 11 characters char Address[50];// address with 49 characters With initialization char identifier=string constant E.g. char name[]=“John”;//name with 5 characters Char choice[]=“a,b,c,d,e”;//choice with 10 characters However, you cannot initialize a string after declaration char name[10]; name=“john”; error C2440: '=' : cannot convert from 'const char [5]' to 'char [10]'

cstring : Reading and Printing 21 The array word can store 20 characters but we can only we up to 19 character (the last character is reserved for null character). #include using namespace std; void main(){ char word[20]; //read a string cin >> word; cout << word; //print a string }

Reading a line of characters 22 cin >> str will terminate when whitespace characters (space, tab, linefeed, carriage-return, formfeed, vertical-tab and newline characters) is encountered Suppose "hello world" is input char s[20]; cin >> s; //read "hello" cin >> s; //read "world" How to read a line of characters?

cin.get 23 #include using namespace std; void main(){ char c; do { cin.get(c); cout << c; }while (c!='\n'); }

cin.get 24 get(): member function of cin to read in one character from input >>: skipping over whitespace but get() won’t Syntax: char c; cin.get(c);

cin.getline 25 Predefined member function of cin to read a line of text (including space) Two arguments: cstring variable to receive the input size of the cstring #include using namespace std; void main(){ char s[20]; while (1){ cin.getline(s,20); cout << “\”” << s << “\”” << endl; }

cin.getline 26 What if Input is longer than the string variable? End of the source characters is reached? Error occurred? Internal state flags (eofbit,failbit,badbit) of cin object will be set To reset those flags, call method clear() of cin. E.g. cin.clear();

Example 27 #include using namespace std; void main(){ char s[5]; while (1){ cin.getline(s,5); cin.clear(); cout << “\”” << s << “\”” << endl; }

The Null Character ‘\0’ 28 The null character,’\0’, is used to mark the end of a cstring ‘\0’ is a single character (although written in two symbols) It is used to distinguishe a cstring variable from an ordinary array of characters (cstring variable must contain the null character

Why need ‘\0’? 29 cstring is stored in main memory continuously Only the starting address of the cstring is stored in cstring variable char s1[]=“Hello World”;// s1=20 char s2[]=“cs2311”; // s2=32 ‘\0’ indicates the end of cstring

Why need ‘\0’? 30 When a cstring variable is passed to a output function, i.e. cout, the function will print all the memory content until ‘\0’ is encountered

Why need ‘\0’? 31 #include using namespace std; void main(){ char s1[]="cs2311"; char s2[]="Hello world"; s2[11]=' '; cout << s2; cout << endl;}

Passing strings to functions 32 Example: Write a function to count the number of occurrences of a character in a string Functions count : given a character and a string as input, return the number of occurrences of the character in the string main function: call count function

Function : count 33 int count(char s[100], char c){ int occurrence=0; int i; //counter for (i=0; s[i]!='\0'; i++){ if (s[i]==c) occurrence++; } return occurrence; } The size 100 is optional

The main function 34 void main(){ char str[50]=”CityU is a very good university"; int count = count(str, 'o'); cout << "count = “ <<count<< “ \n"); }

Another example: string length 35 #include using namespace std; int strlength(char s[]){ int i=0; while (s[i]!=‘\0’) i++; return i; } void main(){ char s[20]="Hello world"; cout << strlength(s); }

36 Other cstring functions Ignore String operations

cstring: copy 37 Suppose there are two strings, str1 and str2 str1 is initialized to "Hello world" Copy str1 to str2 We should NOT use the following expression to copy array elements str2=str1; Similarly, we should NOT use the following expression to compare strings if (str1==str2)......

Idea 38 Use a loop to read characters one by one from str1 until a null character ( '\0' ) is read Copy the character to the corresponding position of str2 Put a null character at the end of str2

The program 39 #include using namespace std; void main(){ char str1[20]="Hello world"; char str2[20]; int i; /*beware of the boundary condition!*/ for (i=0; i<19 && str1[i]!='\0'; i++) { str2[i]=str1[i]; } str2[i]='\0'; cout << str2; }

cstring: length 40 To count the number of characters contained in a string We can use a loop to read characters one by one from the string until a null character ( '\0' ) is read For each character read, increment a counter by one #include using namespace std; void main(){ char s[20]="Hello world"; int len; int i=0; while (s[i]!=‘\0’){ i++; } len=i; }

Common cstring functions in 41 FunctionDescriptionRemarks strcpy (dest,src)Copy the content of string src to the string dest No error check on the size of dest is enough for holding src strcat (dest,src)Append the content of string src onto the end of string dest No error check on the size of dest is enough for holding src strcmp(s1,s2)Lexicographically compare two strings, s1 and s2, character by character. 0: s1 and s2 is identical >0: s1 is greater than s2 <0: s1 is less than s1 strlen(string)Returns the number of characters (exclude the null character) contain in the string

Examples: 42 #include using namespace std; void main(){ char s1[50]="String 1"; char s2[50]="cs2363 computer programming"; cout <<"s1:"<< s1 <<endl; cout <<"s2:" << s2<<endl; strcpy(s1,"cs2311"); cout <<"s1:"<< s1 <<endl; strcat(s1," computer programming"); cout <<"s1:"<< s1 <<endl; cout <<"Compare s1 vs s2:" << strcmp (s1,s2) <<endl; cout <<"Comprare s2 vs s1:" << strcmp (s2,s1) <<endl; cout <<"Compare s1 vs \"cs2311 computer programming\":" << strcmp (s1,"cs2311 computer programming") <<endl; }

Example 43 Write a program to print a word backward. Example: Input: hello Output: olleh

The program 44 #include using namespace std; void main(){ char ____; //define an array input with size 20 int n; //length of str int i; cin >>____; n=______; //compute string length for (i=____; i > 0 ;i--) cout <<____; }

The program 45 #include using namespace std; void main(){ char input[50]; //define an array input with size 50 int n; //length of str int i; cin >> input; n=strlen(input); //compute string length for (i=n-1; i>=0; i--) cout << input[i]; }

Exercise 46 Write a program to let the user to input a line of string from the user The program should reverse the case of the input characters and print the result Lowercase characters are changed to uppercase. Uppercase characters are changed to lower case Example input/output: Hello World hELLO wORLD

Program 47 #include using namespace std; void main(){ char s[20]; int i; cin.getline(s); for (i=0; s[i]!='\0'; i++){ if ( ) //uppercase letter cout << ; //convert to lowercase else if (s[i]>='a' && s[i]<='z') //lowercase letter cout << ; //convert to uppercase else //other characters cout << ; }

Answer 48 #include using namespace std; void main(){ char s[20]; int i; cin.getline(s); for (i=0; s[i]!='\0'; i++){ if (s[i]>='A' && s[i]<='Z') //uppercase letter cout << s[i]+'a'-'A'; //convert to lowercase else if (s[i]>='a' && s[i]<='z') //lowercase letter cout << s[i]+'A'-'a'; //convert to uppercase else //other characters cout << s[i] ; }

cin.ignore (count, delimiter ) 49 Function to skip number of elements from keyboard buffer count: number of elements to skip. delimiter: stop at the point right after “delimiter” is encountered. Example: cin.ignore(1000,’\n’); /* skip at most 1000 characters before ‘\n’ is found, */ cin.ignore(1000,’c’); /* skip at most 1000 characters before ‘c’ is found, */

Example 50 #include using namespace std; void main(){ char name[20]; char address[20]; cin >> name; cin.ignore(1000,'\n'); cin >> address; cout << name <<':'<<address <<endl; }

cin.ignore (count, delimiter ) 51 Store in cstring “name”Discarded by cin Discarded by cin.ignore(..)

Summary 52 Character is an integer cin.get(…), cin.put(…), cin.readline (…), cin.clear(…), cin.ignore(…,…) String is an array of character terminated by ‘\0’ Access string content is similar to access individual element of an array String copy, comparison, concatenate can be done by functions provided by library (also defined in )