SlideShare a Scribd company logo
Absolute C++
Sixth Edition
Chapter 9
Strings
Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
Learning Objectives
9.1 An Array Type for Strings
9.1.1 C-Strings
9.2 Character Manipulation Tools
9.2.1 Character I/O
9.2.2 get, put member functions
9.2.3 putback, peek, ignore
9.3 Standard Class string
9.3.1 String processing
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
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
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
C-String Storage
• A standard array:
char s[10];
– If s contains string “Hi Mom”, stored as:
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:
C-String Indexes
• A c-string IS an array
• Can access indexed variables of:
char ourString[5] = “Hi”;
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!
Library
• Declaring c-strings
– Requires no C++ library
– Built into standard C++
• Manipulations
– Require library <cstring>
– Typically included when using c-strings
▪Normally want to do "fun" things with them
= and == with C-strings
• C-strings not like other variables
– Cannot assign or compare:
–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!
Comparing C-strings
• Also cannot use operator ==
–aString == anotherString; // NOT allowed!
• Must use library function again:
The <cstring> Library: Display 9.1 Some
Predefined C-String Functions in <cstring> (1 of 2)
• Full of string manipulation functions
Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved
The <cstring> Library: Display 9.1 Some
Predefined C-String Functions in <cstring> (2 of 2)
C-string Functions: strlen()
• “String length”
• Often useful to know string length:
–Returns number of characters
▪Not including null
–Result here:
6
C-string Functions: strcat()
• strcat()
• “String concatenate”:
–Note result:
stringVar now contains “The rainin Spain”
–Be careful!
–Incorporate spaces as needed!
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
C-String Output
• Can output with insertion operator, <<
• As we’ve been doing already:
–Where news is a c-string variable
• Possible because << operator is
overloaded for c-strings!
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!
C-String Input Example
• 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”
C-String Line Input
• Can receive entire line into c-string
• Use getline(), a predefined member function:
–Dialogue:
Enter input: Do be do to you!
Do be do to you! END OF INPUT
Example: Command Line Arguments (1 of 3)
• Programs invoked from the command line (e.g. a UNIX
shell, DOS command prompt) can be sent arguments
– Example: COPY C:FOO.TXT D:FOO2.TXT
▪This runs the program named “COPY” and sends in
two C-String parameters, “C:FOO.TXT” and “D:
FOO2.TXT”
▪It is up to the COPY program to process the inputs
presented to it; i.e. actually copy the files
• Arguments are passed as an array of C-Strings to the main
function
Example: Command Line Arguments (2 of 3)
• Header for main
– int main(int argc, char *argv[])
– argc specifies how many arguments are supplied. The
name of the program counts, so argc will be at least 1.
– argv is an array of C-Strings.
▪argv[0] holds the name of the program that is
invoked
▪argv[1] holds the name of the first parameter
▪argv[2] holds the name of the second parameter
▪Etc.
Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved
Example: Command Line Arguments (3 of 3)
More getline()
• Can explicitly tell length to receive:
–Results:
Enter input: dobedowap
dobeEND OF OUTPUT
–Forces FOUR characters only be read
▪Recall need for null character!
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
Member Function get()
• Reads one char at a time
• Member function of cin object:
–Reads next char & puts in variable
nextSymbol
–Argument must be char type
▪Not “string”!a
Member Function put()
• Outputs one character at a time
• Member function of cout object:
• Examples:
• Outputs letter “a” to screen
• Outputs letter “e” to screen
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 © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved
Character-Manipulating Functions: Display
9.3 Some Functions in <cctype> (1 of 3)
Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved
Character-Manipulating Functions: Display
9.3 Some Functions in <cctype> (2 of 3)
Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved
Character-Manipulating Functions: Display
9.3 Some Functions in <cctype> (3 of 3)
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!
Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved
Display 9.4 Program Using the Class string
I/O with Class string
• Just like other types!
• 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”
getline() with Class string
• For complete lines:
string line;
• 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()
Other getline() Versions
• Can specify “delimiter” character:
string line;
–Receives input until “?” encountered
• getline() actually returns reference
–string s1, s2;
getline(cin, s1) >> s2;
–Results in: (cin) >> s2;
Pitfall: Mixing Input Methods
• Be careful mixing cin >> var and getline
–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()!
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 © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved
Display 9.7 Member Functions of the
Standard Class string (1 of 2)
Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved
Display 9.7 Member Functions of the
Standard Class string (2 of 2)
C-string and string Object Conversions
• Automatic type conversions
▪Perfectly legal and appropriate!
–aCString = stringVar;
▪ILLEGAL!
▪Cannot auto-convert to c-string
–Must use explicit conversion:
strcpy(aCString, stringVar.c_str());
Converting between string and numbers
• In C++11 it is simply a matter of calling stof, stod, stoi, or
stol to convert a string to a float, double, int, or long,
respectively.
Converting between numbers and string
objects
• In C++11 use to_string to convert a numeric type to a
string
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
Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved
Copyright

More Related Content

PPT
CPlusPus
PPT
Abhishek lingineni
PPT
C++_programs.ppt
PPT
C++_programs.ppt
PPT
C++ programming: Basic introduction to C++.ppt
PPT
C++_programs.ppt
PPT
C++_programs.ppt
PPT
C++_programs.ppt
CPlusPus
Abhishek lingineni
C++_programs.ppt
C++_programs.ppt
C++ programming: Basic introduction to C++.ppt
C++_programs.ppt
C++_programs.ppt
C++_programs.ppt

Similar to Chapter 9 C++ Programming Absolute C++ Lecture Slides (20)

PPT
C++_programs.ppt
PDF
0-Slot21-22-Strings.pdf
PPTX
C++ process new
PPTX
Should i Go there
PPT
C++ Strings.ppt
PPTX
Learn c++ Programming Language
PPT
Operation on string presentation
PDF
Chapter 3 - Characters and Strings - Student.pdf
PPTX
C101 – Intro to Programming with C
PPTX
Cs1123 3 c++ overview
PPTX
Structure of a C++ Program in computer programming .pptx
PPTX
Review of C.pptx
PPT
Fp201 unit2 1
PPTX
C#unit4
PPTX
unit-5 String Math Date Time AI presentation
PPTX
Chapter1.pptx
PDF
C++ programming intro
PPTX
Character Arrays and strings in c language
PPT
pythegggggeeeeeeeeeeeeeeeeeeeeeeeon1.ppt
C++_programs.ppt
0-Slot21-22-Strings.pdf
C++ process new
Should i Go there
C++ Strings.ppt
Learn c++ Programming Language
Operation on string presentation
Chapter 3 - Characters and Strings - Student.pdf
C101 – Intro to Programming with C
Cs1123 3 c++ overview
Structure of a C++ Program in computer programming .pptx
Review of C.pptx
Fp201 unit2 1
C#unit4
unit-5 String Math Date Time AI presentation
Chapter1.pptx
C++ programming intro
Character Arrays and strings in c language
pythegggggeeeeeeeeeeeeeeeeeeeeeeeon1.ppt
Ad

Recently uploaded (20)

PPTX
Lesson notes of climatology university.
PPTX
master seminar digital applications in india
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Complications of Minimal Access Surgery at WLH
Lesson notes of climatology university.
master seminar digital applications in india
Abdominal Access Techniques with Prof. Dr. R K Mishra
Microbial disease of the cardiovascular and lymphatic systems
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
O7-L3 Supply Chain Operations - ICLT Program
Final Presentation General Medicine 03-08-2024.pptx
Insiders guide to clinical Medicine.pdf
Cell Structure & Organelles in detailed.
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Sports Quiz easy sports quiz sports quiz
FourierSeries-QuestionsWithAnswers(Part-A).pdf
GDM (1) (1).pptx small presentation for students
human mycosis Human fungal infections are called human mycosis..pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Complications of Minimal Access Surgery at WLH
Ad

Chapter 9 C++ Programming Absolute C++ Lecture Slides

  • 1. Absolute C++ Sixth Edition Chapter 9 Strings Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
  • 2. Learning Objectives 9.1 An Array Type for Strings 9.1.1 C-Strings 9.2 Character Manipulation Tools 9.2.1 Character I/O 9.2.2 get, put member functions 9.2.3 putback, peek, ignore 9.3 Standard Class string 9.3.1 String processing
  • 3. 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
  • 4. 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
  • 5. 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
  • 6. C-String Storage • A standard array: char s[10]; – If s contains string “Hi Mom”, stored as:
  • 7. 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:
  • 8. C-String Indexes • A c-string IS an array • Can access indexed variables of: char ourString[5] = “Hi”;
  • 9. 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!
  • 10. Library • Declaring c-strings – Requires no C++ library – Built into standard C++ • Manipulations – Require library <cstring> – Typically included when using c-strings ▪Normally want to do "fun" things with them
  • 11. = and == with C-strings • C-strings not like other variables – Cannot assign or compare: –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!
  • 12. Comparing C-strings • Also cannot use operator == –aString == anotherString; // NOT allowed! • Must use library function again:
  • 13. The <cstring> Library: Display 9.1 Some Predefined C-String Functions in <cstring> (1 of 2) • Full of string manipulation functions
  • 14. Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved The <cstring> Library: Display 9.1 Some Predefined C-String Functions in <cstring> (2 of 2)
  • 15. C-string Functions: strlen() • “String length” • Often useful to know string length: –Returns number of characters ▪Not including null –Result here: 6
  • 16. C-string Functions: strcat() • strcat() • “String concatenate”: –Note result: stringVar now contains “The rainin Spain” –Be careful! –Incorporate spaces as needed!
  • 17. 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
  • 18. C-String Output • Can output with insertion operator, << • As we’ve been doing already: –Where news is a c-string variable • Possible because << operator is overloaded for c-strings!
  • 19. 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!
  • 20. C-String Input Example • 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”
  • 21. C-String Line Input • Can receive entire line into c-string • Use getline(), a predefined member function: –Dialogue: Enter input: Do be do to you! Do be do to you! END OF INPUT
  • 22. Example: Command Line Arguments (1 of 3) • Programs invoked from the command line (e.g. a UNIX shell, DOS command prompt) can be sent arguments – Example: COPY C:FOO.TXT D:FOO2.TXT ▪This runs the program named “COPY” and sends in two C-String parameters, “C:FOO.TXT” and “D: FOO2.TXT” ▪It is up to the COPY program to process the inputs presented to it; i.e. actually copy the files • Arguments are passed as an array of C-Strings to the main function
  • 23. Example: Command Line Arguments (2 of 3) • Header for main – int main(int argc, char *argv[]) – argc specifies how many arguments are supplied. The name of the program counts, so argc will be at least 1. – argv is an array of C-Strings. ▪argv[0] holds the name of the program that is invoked ▪argv[1] holds the name of the first parameter ▪argv[2] holds the name of the second parameter ▪Etc.
  • 24. Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved Example: Command Line Arguments (3 of 3)
  • 25. More getline() • Can explicitly tell length to receive: –Results: Enter input: dobedowap dobeEND OF OUTPUT –Forces FOUR characters only be read ▪Recall need for null character!
  • 26. 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
  • 27. Member Function get() • Reads one char at a time • Member function of cin object: –Reads next char & puts in variable nextSymbol –Argument must be char type ▪Not “string”!a
  • 28. Member Function put() • Outputs one character at a time • Member function of cout object: • Examples: • Outputs letter “a” to screen • Outputs letter “e” to screen
  • 29. 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”
  • 30. Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved Character-Manipulating Functions: Display 9.3 Some Functions in <cctype> (1 of 3)
  • 31. Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved Character-Manipulating Functions: Display 9.3 Some Functions in <cctype> (2 of 3)
  • 32. Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved Character-Manipulating Functions: Display 9.3 Some Functions in <cctype> (3 of 3)
  • 33. 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!
  • 34. Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved Display 9.4 Program Using the Class string
  • 35. I/O with Class string • Just like other types! • 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”
  • 36. getline() with Class string • For complete lines: string line; • 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()
  • 37. Other getline() Versions • Can specify “delimiter” character: string line; –Receives input until “?” encountered • getline() actually returns reference –string s1, s2; getline(cin, s1) >> s2; –Results in: (cin) >> s2;
  • 38. Pitfall: Mixing Input Methods • Be careful mixing cin >> var and getline –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()!
  • 39. 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
  • 40. Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved Display 9.7 Member Functions of the Standard Class string (1 of 2)
  • 41. Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved Display 9.7 Member Functions of the Standard Class string (2 of 2)
  • 42. C-string and string Object Conversions • Automatic type conversions ▪Perfectly legal and appropriate! –aCString = stringVar; ▪ILLEGAL! ▪Cannot auto-convert to c-string –Must use explicit conversion: strcpy(aCString, stringVar.c_str());
  • 43. Converting between string and numbers • In C++11 it is simply a matter of calling stof, stod, stoi, or stol to convert a string to a float, double, int, or long, respectively.
  • 44. Converting between numbers and string objects • In C++11 use to_string to convert a numeric type to a string
  • 45. 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
  • 46. Copyright © 2016,2013,2011 Pearson Education, Inc. All Rights Reserved Copyright

Editor's Notes

  • #1: If this PowerPoint presentation contains mathematical equations, you may need to check that your computer has the following installed: 1) MathType Plugin 2) Math Player (free versions available) 3) NVDA Reader (free versions available)
  • #2: Headings should be set in title case and blue colour. (Title case means capitalizing the first letter of each words that are not articles or prepositions, e.g. Road Map to Success. It does not mean all caps.)
  • #46: If this slide was not included in the original PPT, it should be added.