Chapter 9. Strings. 國立雲林科技大學資訊工程研究所張傳育 (Chuan Yu Chang ) 博士

Similar documents
Ch 6-8. C-Strings. April 30, Prof. Young-Tak Kim

Copyright 2003 Pearson Education, Inc. Slide 1

In this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Engineering Problem Solving with C++, Etter

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

File I/O and String Manipula3ons CS 16: Solving Problems with Computers I Lecture #11

I/O Streams and Standard I/O Devices (cont d.)

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Software Design & Programming I

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

Strings in C++ Dr. Ferdin Joe John Joseph Kamnoetvidya Science Academy

Lecture 12. We have already used strings. Strings. Hello Class is a string.

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

More File Operations. Lecture 17 COP 3014 Spring april 18, 2018

The C++ Language. Arizona State University 1

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3 - Notes Input/Output

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1

Week 3: File I/O and Formatting 3.7 Formatting Output

BITG 1113: Array (Part 2) LECTURE 9

More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10

String Objects: The string class library

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

CSCI 1061U Programming Workshop 2. C++ Basics

LECTURE 15. String I/O and cstring library

File I/O CS 16: Solving Problems with Computers I Lecture #9

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

Module C++ I/O System Basics

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

Absolute C++ Walter Savitch

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

String Variables and Output/Input. Adding Strings and Literals to Your Programming Skills and output/input formatting

Chapter 7: User-Defined Simple Data Types, Namespaces, and the string Type

CPE Summer 2015 Exam I (150 pts) June 18, 2015

Name. CPTR246 Spring '17 (100 total points) Exam 2

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points.

Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

CS 103 Lab - Party Like A Char Star

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Chapter 10: Characters, C- Strings, and More About the string Class Character Testing

Programming with C++ as a Second Language

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

CS3157: Advanced Programming. Outline

Objectives. In this chapter, you will:

Chapter 10 Characters, Strings, and the string class

Programming. C++ Basics

Expressions, Input, Output and Data Type Conversions

System Design and Programming II

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Definition Matching (10 Points)

Chapter 2: Introduction to C++

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

EE 355 Lab 4 - Party Like A Char Star

Programming in C/C

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Assignment 5: MyString COP3330 Fall 2017

CS 103 Lab 6 - Party Like A Char Star

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Chapter 10: Character Testing. From Program Character Case Conversion 8/23/2014. Character Testing. Character Case Conversion

Chapter 10: Characters, C- Strings, and More About the string Class

3.1. Chapter 3: The cin Object. Expressions and Interactivity

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Applied C and C++ Programming

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

Getting started with C++ (Part 2)

2 nd Week Lecture Notes

Problem Solving with C++

8. Control statements

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

C++ Input/Output Chapter 4 Topics

Note 11/13/2014. They are like those i s, j s, and temp s that appear and disappear when the function starts and finishes...

13 4 Understanding Character Strings

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

120++: a C++ Subset Corresponding to A Project-Based Introduction to C++

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object

Chapter 3: Expressions and Interactivity

Lecture 3 The character, string data Types Files

Object Oriented Programming COP3330 / CGS5409

CSc Introduc/on to Compu/ng. Lecture 17 Edgardo Molina Fall 2011 City College of New York

Transcription:

Chapter 9 Strings 國立雲林科技大學資訊工程研究所張傳育 (Chuan Yu Chang ) 博士 Office: EB 212 TEL: 05 5342601 ext. 4337 E mail: chuanyu@yuntech.edu.tw HTTP://MIPL.yuntech.edu.tw Copyright 2008 Pearson Addison Wesley. All rights reserved

Learning Objectives An Array Type for Strings C Strings Character Manipulation Tools Character I/O get, put member functions putback, peek, ignore Standard Class string String processing 9 2

Introduction Two string types: C strings Array with base type char End of string marked with null, "\0" "Older" method inherited from C String class Uses templates 9 3

C Strings Array with base type char One character per indexed variable One extra character: "\0" Called "null character" End marker We ve used c strings Literal "Hello" stored as c string 9 4

C String Variable Array of characters: char s[10]; Declares a c string variable to hold up to 9 characters + one null character Typically "partially filled" array Declare large enough to hold max size string Indicate end with null Only difference from standard array: Must contain null character 9 5

C String Storage A standard array: char s[10]; If s contains string "Hi Mom!", stored as: 9 6

C String Initialization Can initialize c string: char mymessage[20] = "Hi there."; Needn t fill entire array Initialization places "\0" at end Can omit array size: char shortstring[] = "abc"; Automatically makes size one more than length of quoted string. abc\0 NOT same as: char shortstring[] = {"a", "b", "c"}; abc 9 7

A c string is an array C String Indexes Can access indexed variables of: char ourstring[5] = "Hi"; ourstring[0] is "H" ourstring[1] is "i" ourstring[2] is "\0" ourstring[3] is unknown ourstring[4] is unknown 9 8

C String Index Manipulation Can manipulate indexed variables char happystring[7] = "DoBeDo"; happystring[6] = "Z"; Be careful! Here, "\0" (null) was overwritten by a "Z"! If null overwritten, c string no longer "acts" like c string! Unpredictable results! 9 9

Library Declaring c strings Requires no C++ library Built into standard C++ Manipulations Require library <cstring> #include <cstring> Typically included when using c strings Normally want to do "fun" things with them 9 10

= and == with C strings C strings not like other variables Cannot assign or compare: char astring[10]; astring = "Hello"; // ILLEGAL! Can ONLY use "=" at declaration of c string! Must use library function for assignment: strcpy(astring, "Hello"); Built in function (in <cstring>) Sets value of astring equal to "Hello" NO checks for size! Up to programmer, just like other arrays! 9 11

Comparing C strings Also cannot use operator == char astring[10] = "Hello"; char anotherstring[10] = "Goodbye"; astring == anotherstring; // NOT allowed! Must use library function again: if (strcmp(astring, anotherstring)) cout << "Strings NOT same."; else cout << "Strings are same."; 9 12

The <cstring> Library: Display 9.1 Some Predefined C String Functions in <cstring> (1 of 2) Full of string manipulation functions 9 13

The <cstring> Library: Display 9.1 Some Predefined C String Functions in <cstring> (2 of 2) 9 14

C string Functions: strlen() "String length" Often useful to know string length: char mystring[10] = "dobedo"; cout << strlen(mystring); Returns number of characters Not including null Result here: 6 9 15

C string Functions: strcat() strcat() 字串連接 (String concatenate) : char stringvar[20] = "The rain"; strcat(stringvar, "in Spain"); Note result: stringvar now contains "The rainin Spain" Be careful! Incorporate spaces as needed! 9 16

C string Arguments and Parameters A c string variable is an array So c string parameter is array parameter C strings passed to functions can be changed by receiving function! Like all arrays, typical to send size as well Function "could" also use "\0" to find end So size not necessary if function won t change c string parameter Use "const" modifier to protect c string arguments 9 17

C String Output Can output with insertion operator, << As we ve been doing already: cout << news << " Wow.\n"; where news is a c string variable Possible because << operator is overloaded for c strings! 9 18

C String Input Can input with extraction operator, >> Issues exist, however Whitespace is "delimiter" Tab, space, line breaks are "skipped" Input reading "stops" at delimiter Watch size of c string Must be large enough to hold entered string! C++ gives no warnings of such issues! 9 19

C String Input Example char a[80], b[80]; cout << "Enter input: "; cin >> a >> b; cout << a << b << "END OF OUTPUT\n"; Dialogue offered: Enter input: Do be do to you! DobeEND OF OUTPUT Note: Underlined portion typed at keyboard C string a receives: Do" C string b receives: "be" 9 20

C String Line Input Can receive entire line into c string Use getline(), a predefined member function: char a[80]; cout << "Enter input: "; cin.getline(a, 80); cout << a << "END OF OUTPUT\n"; Dialogue: Enter input: Do be do to you! Do be do to you!end OF INPUT 9 21

More getline() Can explicitly tell length to receive: char shortstring[5]; cout << "Enter input: "; cin.getline (shortstring, 5); cout << shortstring << "END OF OUTPUT\n"; Results: Enter input: dobedowap dobeend OF OUTPUT Forces FOUR characters only be read need for null character! 9 22

Character I/O Input and output data ALL treated as character data e.g., number 10 outputted as 1 and 0 Conversion done automatically Uses low level utilities Can use same low level utilities ourselves as well 9 23

Member Function get() Reads one char at a time Member function of cin object: char nextsymbol; cin.get(nextsymbol); Reads next char & puts in variable nextsymbol Argument must be char type Not "string"! char ca, c2, c3; cin.get(c1); cin.get(c2); cin.get(c3); Suppose we type in the following two lines of input AB CD The value of c1, c2, and c3 are c1= A, c2= B, c3= \n 9 24

Member Function put() Outputs one character at a time Member function of cout object: Examples: cout.put( a ); Outputs letter a to screen char mystring[10] = "Hello"; cout.put(mystring[1]); Outputs letter e to screen 9 25

More Member Functions putback() Once read, might need to "put back" cin.putback(lastchar); peek() Returns next char to be read by cin, but leaves it there peekchar = cin.peek(); ignore() Skip input, up to designated character cin.ignore(1000, "\n"); Skips at most 1000 characters until "\n" 9 26

Character Manipulating Functions: Display 9.3 Some Functions in <cctype> (1 of 3) 9 27

Character Manipulating Functions: Display 9.3 Some Functions in <cctype> (2 of 3) 9 28

Character Manipulating Functions: Display 9.3 Some Functions in <cctype> (3 of 3) 9 29

Standard Class string Defined in library: #include <string> using namespace std; String variables and expressions Treated much like simple types Can assign, compare, add: string s1, s2, s3; s3 = s1 + s2; //Concatenation s3 = "Hello Mom!" //Assignment Note c string "Hello Mom!" automatically converted to string type! 9 30

Display 9.4 Program Using the Class string 9 31

I/O with Class string Just like other types! string s1, s2; cin >> s1; cin >> s2; Suppose user types in: May the hair on your toes grow long and curly! Extraction still ignores whitespace: s1 receives value "May" s2 receives value "the" 9 32

getline() with Class string For complete lines: string line; cout << "Enter a line of input: "; getline(cin, line); cout << line << "END OF OUTPUT"; Dialogue produced: Enter a line of input: Do be do to you! Do be do to you!end OF INPUT Similar to c string s usage of getline() 9 33

Other getline() Versions Can specify "delimiter" character: string line; cout << "Enter input: "; getline(cin, line, "?"); Receives input until "?" encountered getline() actually returns reference string s1, s2; { getline(cin, s1) >> s2; Results in: cin >> s2; main() } string s1,s2; getline(cin,s1)>>s2; cout<<s1; cout<<s2; system("pause"); 9 34

Pitfall: Mixing Input Methods Be careful mixing cin >> variable and getline int n; string line; cin >> n; getline(cin, line); If input is: 42 Hello hitchhiker. Variable n set to 42 line set to empty string! cin >> n skipped leading whitespace, leaving "\n" on stream for getline()! So getline reads an empty string. 9 35

Class string Processing Same operations available as c strings And more! Over 100 members of standard string class Some member functions:.length() Returns length of string variable.at(i) Returns reference to char at position i 9 36

Display 9.7 Member Functions of the Standard Class string (1 of 2) 9 37

Display 9.7 Member Functions of the Standard Class string (2 of 2) 9 38

C string and string Object Conversions Automatic type conversions From c string to string object: char acstring[] = "My C-string"; string stringvar; stringvar = acstring; Perfectly legal and appropriate! acstring = stringvar; ILLEGAL! Cannot auto convert to c string Must use explicit conversion: strcpy(acstring, stringvar.c_str()); 9 39

Summary C string variable is "array of characters" With addition of null character, "\0" C strings act like arrays Cannot assign, compare like simple variables Libraries <cctype> & <string> have useful manipulating functions cin.get() reads next single character getline() versions allow full line reading Class string objects are better behaved than c strings 9 40