Copyright © 2002 Pearson Education, Inc. Slide 1.

Slides:



Advertisements
Similar presentations
Chapter 9 Strings. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 Learning Objectives An Array Type for Strings C-Strings Character.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 1 Overview 8.1 An Array Type for Strings 8.2 The Standard string.
Chapter 10.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8 Strings and Vectors.
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.
Programming Strings. COMP102 Prog. Fundamentals: Strings / Slide 2 Character Strings l A sequence of characters is often referred to as a character “string”.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
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.
C-strings Array with base type char One character per indexed variable
ACS 168 Structured Programming Using the Computer Spring 2002 Joaquin Vila Prepared by Shirley White.
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.
Working with Strings Lecture 2 Hartmut Kaiser
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Array with base type char One character per indexed variable One extra character: '\0' Called ‘null character’ Delimiter of the string To declare a string,
Chapter 1 Working with strings. Objectives Understand simple programs using character strings and the string library. Get acquainted with declarations,
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
9-1 Learning Objectives  An Array Type for Strings  C-Strings.
1 Problem Solving with C++ The Object of Programming Walter Savitch Chapter 10 Strings and Multidimensional Arrays Slides by David B. Teague, Western Carolina.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10: Characters, Strings, and the string class.
Characters, Strings, And The string Class Chapter 10.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 8 Strings and Vectors.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8 Strings and Vectors.
String Class. C-style and C++ string Classes C-style strings, called C-strings, consist of characters stored in an array ( we’ll look at them later) C++
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 10: Characters, C- Strings, and More About.
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
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
CSC 270 – Survey of Programming Languages
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students C-strings and strings.
Chapter 9 Strings. Learning Objectives An Array Type for Strings – C-Strings Character Manipulation Tools – Character I/O – get, put member functions.
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
C/C++ Basics (VI) Strings and Vectors Berlin Chen 2003 Textbook: 1. Walter Savitch, “Absolute C++,” Addison Wesley, 2002 開發代理 2. Walter Savitch, “Problem.
An Array Type For Strings. Two ways to represent strings – i.e. “Hello” cstring An array with base type char Older way of processing strings Null character.
An Introduction to Programming with C++ Sixth Edition Chapter 13 Strings.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 8 Strings and Vectors. Slide 8- 2 Overview 8.1 An Array Type for Strings 8.2 The Standard string Class 8.3 Vectors.
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
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Chapter 8 Strings and Vectors 1
Chapter 8 Strings and Vectors
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Strings (part 2) Dr. Xiao Qin Auburn.
Chapter 9 Strings Copyright © 2016 Pearson, Inc. All rights reserved.
Standard Version of Starting Out with C++, 4th Edition
Learning Objectives String Class.
Working with Strings Lecture 2 Hartmut Kaiser
C-Strings, Strings, Vectors, STL
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
String What it is Why it’s useful
C-strings In general, a string is a series of characters treated as a unit. Practically all string implementations treat a string as a variable-length.
Chapter 9 Strings Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Standard Version of Starting Out with C++, 4th Edition
getline() function with companion ignore()
Presentation transcript:

Copyright © 2002 Pearson Education, Inc. Slide 1

Copyright © 2002 Pearson Education, Inc. Slide 2 Chapter 9 Created by Frederick H. Colclough, Colorado Technical University Strings

Copyright © 2002 Pearson Education, Inc. Slide 3 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

Copyright © 2002 Pearson Education, Inc. Slide 4 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

Copyright © 2002 Pearson Education, Inc. Slide 5 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

Copyright © 2002 Pearson Education, Inc. Slide 6 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

Copyright © 2002 Pearson Education, Inc. Slide 7 C-String Storage  A standard array: char s[10];  If s contains string “Hi Mom”, stored as: Display page 352

Copyright © 2002 Pearson Education, Inc. Slide 8 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  NOT same as: char shortString[] = {‘a’, ‘b’, ‘c’};

Copyright © 2002 Pearson Education, Inc. Slide 9 C-String Indexes  A c-string IS an array  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

Copyright © 2002 Pearson Education, Inc. Slide 10 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!

Copyright © 2002 Pearson Education, Inc. Slide 11 Library  Declaring c-strings  Requires no C++ library  Built into standard C++  Manipulations  Require library  Typically included when using c-strings  Normally want to do ‘fun’ things with them

Copyright © 2002 Pearson Education, Inc. Slide 12 = 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 )  Sets value of aString equal to “Hello”  NO checks for size!  Up to programmer, just like other arrays!

Copyright © 2002 Pearson Education, Inc. Slide 13 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.”;

Copyright © 2002 Pearson Education, Inc. Slide 14 The Library  Full of string manipulation functions Display 9.1, page 357

Copyright © 2002 Pearson Education, Inc. Slide 15 The Library Cont’d  Full of string manipulation functions Display 9.1, page 357

Copyright © 2002 Pearson Education, Inc. Slide 16 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

Copyright © 2002 Pearson Education, Inc. Slide 17 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!

Copyright © 2002 Pearson Education, Inc. Slide 18 C-string Arguments and Parameters  Recall: c-string is 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

Copyright © 2002 Pearson Education, Inc. Slide 19 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!

Copyright © 2002 Pearson Education, Inc. Slide 20 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!

Copyright © 2002 Pearson Education, Inc. Slide 21 C-String Input Example  char a[80], b[80]; cout > 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”

Copyright © 2002 Pearson Education, Inc. Slide 22 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

Copyright © 2002 Pearson Education, Inc. Slide 23 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  Recall need for null character!

Copyright © 2002 Pearson Education, Inc. Slide 24 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

Copyright © 2002 Pearson Education, Inc. Slide 25 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’!

Copyright © 2002 Pearson Education, Inc. Slide 26 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

Copyright © 2002 Pearson Education, Inc. Slide 27 More Member Functions  putback()  Once read, might need to ‘put back’  cin.putback(lastChar);  peek()  Returns next char, 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’

Copyright © 2002 Pearson Education, Inc. Slide 28 Character-Manipulating Functions Display 9.3, page

Copyright © 2002 Pearson Education, Inc. Slide 29 Character-Manipulating Functions Cont’d Display 9.3, page

Copyright © 2002 Pearson Education, Inc. Slide 30 Standard Class string  Defined in library: #include 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!

Copyright © 2002 Pearson Education, Inc. Slide 31 Program Using Class string Display 9.4, page 377

Copyright © 2002 Pearson Education, Inc. Slide 32 I/O with Class string  Just like other types!  string s1, s2; cin >> s1; cin >> s2;  Results: 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”

Copyright © 2002 Pearson Education, Inc. Slide 33 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()

Copyright © 2002 Pearson Education, Inc. Slide 34 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;

Copyright © 2002 Pearson Education, Inc. Slide 35 Pitfall: Mixing Input Methods  Be careful mixing cin >> var 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()!

Copyright © 2002 Pearson Education, Inc. Slide 36 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

Copyright © 2002 Pearson Education, Inc. Slide 37 Class string Member Functions Display 9.7, page 386

Copyright © 2002 Pearson Education, Inc. Slide 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());

Copyright © 2002 Pearson Education, Inc. Slide 39 Demo 1 //Program to demonstrate the functions newLine and getInput. #include using namespace std; void newLine( ); //Discards all the input remaining on the current input line. //Also discards the '\n' at the end of the line. void getInt(int& number); //Sets the variable number to a //value that the user approves of.

Copyright © 2002 Pearson Education, Inc. Slide 40 Demo 1 continued int main( ) { int n; getInt(n); cout << "Final value read in = " << n << endl << "End of demonstration.\n"; return 0; }

Copyright © 2002 Pearson Education, Inc. Slide 41 Demo 1 continued void newLine( ) { char symbol; do { cin.get(symbol); } while (symbol != '\n'); }

Copyright © 2002 Pearson Education, Inc. Slide 42 Demo 1 continued void getInt(int& number) { char ans; do { cout << "Enter input number: "; cin >> number; cout << "You entered " << number << " Is that correct? (yes/no): "; cin >> ans; newLine( ); } while ((ans == 'N') || (ans == 'n')); }

Copyright © 2002 Pearson Education, Inc. Slide 43 Demo 2 //Demonstrates the standard class string. #include using namespace std; int main( ) { string phrase; string adjective("fried"), noun("ants"); string wish = "Bon appetite!"; phrase = "I love " + adjective + " " + noun + "!"; cout << phrase << endl << wish << endl; return 0; }

Copyright © 2002 Pearson Education, Inc. Slide 44 Demo 3 //Demonstrates getline and cin.get. #include using namespace std; void newLine( ); int main( ) { string firstName, lastName, recordName; string motto = "Your records are our records."; cout << "Enter your first and last name:\n"; cin >> firstName >> lastName; newLine( ); recordName = lastName + ", " + firstName; cout << "Your name in our records is: "; cout << recordName << endl; cout << "Our motto is\n" << motto << endl; cout << "Please suggest a better (one line) motto:\n"; getline(cin, motto); cout << "Our new motto will be:\n"; cout << motto << endl; return 0; }

Copyright © 2002 Pearson Education, Inc. Slide 45 Demo 4 //Demonstrates using a string object as if it were an array. #include using namespace std; int main( ) { string firstName, lastName; cout << "Enter your first and last name:\n"; cin >> firstName >> lastName; cout << "Your last name is spelled:\n"; int i; for (i = 0; i < lastName.length( ); i++) { cout << lastName[i] << " "; lastName[i] = '-'; } cout << endl; for (i = 0; i < lastName.length( ); i++) cout << lastName[i] << " "; //Places a "-" under each letter. cout << endl; cout << "Good day " << firstName << endl; return 0; }

Copyright © 2002 Pearson Education, Inc. Slide 46 Demo 5 //Test for palindrome property. #include using namespace std; void swap(char& v1, char& v2); //Interchanges the values of v1 and v2. string reverse(const string& s); //Returns a copy of s but with characters in reverse order. string removePunct(const string& s, const string& punct); //Returns a copy of s with any occurrences of characters //in the string punct removed. string makeLower (const string& s); //Returns a copy of s that has all upper case //characters changed to lower case, other characters unchanged. bool isPal(const string& s); //Returns true if s is a palindrome, false otherwise.

Copyright © 2002 Pearson Education, Inc. Slide 47 Demo 5 continued int main( ) { string str; cout << "Enter a candidate for palindrome test\n" << "followed by pressing return.\n"; getline(cin, str); if (isPal(str)) cout << "\"" << str + "\" is a palindrome."; else cout << "\"" << str + "\" is not a palindrome."; cout << endl; return 0; }

Copyright © 2002 Pearson Education, Inc. Slide 48 Demo 5 continued void swap(char& v1, char& v2) { char temp = v1; v1 = v2; v2 = temp; } string reverse(const string& s) { int start = 0; int end = s.length( ); string temp(s); while (start < end) { end--; swap(temp[start], temp[end]); start++; } return temp; }

Copyright © 2002 Pearson Education, Inc. Slide 49 Demo 5 continued //Uses and string makeLower(const string& s) { string temp(s); for (int i = 0; i < s.length( ); i++) temp[i] = tolower(s[i]); return temp; }

Copyright © 2002 Pearson Education, Inc. Slide 50 Demo 5 continued string removePunct(const string& s, const string& punct) { string noPunct; //initialized to empty string int sLength = s.length( ); int punctLength = punct.length( ); for (int i = 0; i < sLength; i++) { string aChar = s.substr(i,1); //A one character string int location = punct.find(aChar, 0); //Find location of successive characters //of src in punct. if (location = punctLength) noPunct = noPunct + aChar; //aChar not in punct, so keep it } return noPunct; }

Copyright © 2002 Pearson Education, Inc. Slide 51 Demo 5 continued //uses functions makeLower, removePunct. bool isPal(const string& s) { string punct(",;:.?!'\" "); //includes a blank string str(s); str = makeLower(str); string lowerStr = removePunct(str, punct); return (lowerStr == reverse(lowerStr)); }

Copyright © 2002 Pearson Education, Inc. Slide 52 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 & 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