Sahar Mosleh California State University San MarcosPage 1 The C++ String Class The contents of this particular lecture prepared by the instructors at the.

Slides:



Advertisements
Similar presentations
Getting Data into Your Program
Advertisements

LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Classes and Data Abstraction Lecture 9. Objects Models of things in the real world Defined in classes  Class name is the object name Example: Library.
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.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
File streams Chapter , ,
CPS120: Introduction to Computer Science Lecture 15 B Data Files.
Chapter 10.
C++ Data Type String A string is a sequence of characters enclosed in double quotes. Examples of strings: “Hello” “CIS 260” “Students” The empty string.
1 CS 105 Lecture 8 Strings; Input Failure Mon, Mar 7, 2011, 3:39 pm.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
 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.
PHYS 2020 Making Choices; Arrays. Arrays  An array is very much like a matrix.  In the C language, an array is a collection of variables, all of the.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
1 File I/O In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
Computer Science 1620 Strings. Programs are often called upon to store and manipulate text word processors chat databases webpages etc.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
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.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 4: Continuing with C++ I/O Basics.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 CS161 Introduction to Computer Science Topic #13.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
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.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 5: Continuing with C++ I/O Basics.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
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 
1 Character Strings (Cstrings) Reference: CS215 textbook pages
CSC 270 – Survey of Programming Languages
Chapter 3 Working with Batches of Data. Objectives Understand vector class and how it can be used to collect, store and manipulate data. Become familiar.
String Class Mohamed Shehata 1020: Introduction to Programming.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Sahar Mosleh California State University San MarcosPage 1 Character String.
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Sahar Mosleh California State University San MarcosPage 1 One Dimensional Arrays: Structured data types.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Writing to Files and Reading From Files. Writing Data to a File Creating a new file, a.dat or.txt file #include #include // for file writing #include.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
Library Functions. CSCE 1062 Outline  cmath class library functions {section 3.2}  iomanip class library functions {section 8.5}  string class library.
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
Strings.
Basic concepts of C++ Presented by Prof. Satyajit De
Strings CSCI 112: Programming in C.
Object Oriented Programming COP3330 / CGS5409
Engineering 1020: Introduction to Programming Fall 2018
Introduction to C++ Programming
Chapter 9 Strings Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
File I/O in C++ I.
CPS120: Introduction to Computer Science
character manipulation
File I/O in C++ I.
Presentation transcript:

Sahar Mosleh California State University San MarcosPage 1 The C++ String Class The contents of this particular lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh

Sahar Mosleh California State University San MarcosPage 2 The C++ String Class - Strings are defined in the Standard Class Library - while not part of the language, any standard compiler will include this class in its library - This depends on the compiler - writers - you have to rely on the fact that they've properly implemented the same string operations that everybody else does - To obtain the String Class library use #include

Sahar Mosleh California State University San MarcosPage 3 The C++ String Class - To declare a variable of type string: #include // declaring 3 variables of type string string play, author, mainCharacter; - We can assign to strings: play = “Hamlet”; author = “W. Shakespeare”; mainCharacter = play; // assign to string - Notice: we don’t worry about the length!

Sahar Mosleh California State University San MarcosPage 4 String Class I/O - Do I/O on a string in a natural way: string name = “Jim Anderson”; cout << “My name is ” << name << endl; - The output is: My name is Jim Anderson

Sahar Mosleh California State University San MarcosPage 5 String Class I/O - String class input: cin >> name; // reads first word from input stream cout << name; - Suppose user enter “Marky Ramone” program prints “Marky” (not “Marky Ramone”) - >> skips over whitespace characters, reads next word (until next whitespace character) - Notice the difference << print out the entire string >> read in the next (whitespace delimited) word

Sahar Mosleh California State University San MarcosPage 6 String Class I/O - Often want to read the entire line of text (up to and including the newline character) - the string class has the getline function getline(cin, name); // read next line into name - if I type This is CS211 then string variable name will contain This is CS211

Sahar Mosleh California State University San MarcosPage 7 String Class I/O - A simple program to copy one file to another #include int main() { string line; ifstream infile; ofstream outfile; infile.open("infile.txt"); outfile.open("outfile.txt"); getline(infile,line); while (!infile.eof()) { outfile << line << endl; // note: need endl getline(infile, line); } infile.close(); outfile.close(); }

Sahar Mosleh California State University San MarcosPage 8 String Element Access - Access and modify individual characters of a string, much like an array of char: - Example: string line; line = "This is a line of text"; cout << line[5]; line[2]= 'u'; cout << line << endl; - Output: iThus is a line of text

Sahar Mosleh California State University San MarcosPage 9 String Element Access - String bounds are checked: - access a string at an index beyond the last character (or <0) causes a run-time error - Where is the end of the string? - there is a size() function, which returns the current length of the string

Sahar Mosleh California State University San MarcosPage 10 String Element Access - Example of "size" function: string name=“Adam Smith"; cout << name << " has " << name.size() << " characters in his name" << endl; - Output: Adam Smith has 10 characters in his name - Characters are stored at indices

Sahar Mosleh California State University San MarcosPage 11 Strings: Dynamic Data - Strings are a dynamic data type in that the length can be different at different points in the program execution: string quote; quote = "I am a student at CSUSM."; cout << quote.size() << " "; quote = "I am a student."; cout << quote.size() << endl; - Output: 24 15

Sahar Mosleh California State University San MarcosPage 12 Strings as Parameters - Strings behave "normally" when used as parameters - can be passed by value, or reference (with &) - unlike C-style strings, or arrays of chars for that matter, which are always passed by reference - can still use size() inside a function - the whole object gets passed, all members are accessible - can be returned from functions - unlike C-style strings which can't be easily returned from functions - Essentially, strings behave like ints when used as parameters/return values

Sahar Mosleh California State University San MarcosPage 13 Strings as Value Parameters string reverse(string line) { int i; char tmp; for (i= 0; i< line.size()/2; i++) { tmp= line[i]; line[i]= line[line.size()-1-i]; line[line.size()-1-i] = tmp; } return line; }

Sahar Mosleh California State University San MarcosPage 14 Strings as Value Parameters - Call this function as follows: string line1, line2; line1= “This is Adam Smith"; line2= reverse( line1); cout << line1 << endl; cout << line2 << endl; - The output is: This is Adam Smith htimS madA si sihT - Note: line1 does not change!

Sahar Mosleh California State University San MarcosPage 15 Strings as Reference Parameters - Use a reference parameter void reverse2( string& line) { int i; char tmp; for (i= 0; i<line.size()/2; i++) { tmp= line[i]; line[i]= line[line.size()-1-i]; line[line.size()-1-i]= tmp; } - line is now a reference parameter

Sahar Mosleh California State University San MarcosPage 16 Strings as Reference Parameters - Try out reverse2: string line1, line2; line1="This is Mr. Brown"; cout << line1 << endl; reverse2(line1); cout << line1 << endl; - Output: This is Mr. Brown nworB.rM si sihT

Sahar Mosleh California State University San MarcosPage 17 String Relational Operators - The string class provides many operators and functions which work with strings - Relational operators - strings can be compared much like integers using the operators ==, !=,, >= - the equality operator (==) and inequality operator (!=) work as you would expect.

Sahar Mosleh California State University San MarcosPage 18 String Operators: Concatenation - Another operator provided by the string class library is concatenation using +: string word1, word2, word3, line="I "; word1="am "; word2=”an "; word3="instructor in this college" ; line= line+ word1 + word2 + word3; cout << line << " " << line.size() << endl; - Output: I am an instructor in this college 34 - Notice: the string line grew dynamically!

Sahar Mosleh California State University San MarcosPage 19 String Operators: Concatenation - This is an example of operator overloading - operator + is used for ints, floats, and strings - has a different meaning in each case - operator + for strings is actually not part of C++ - it is part of the C++ class library - you can (in the future) define your own meanings for various operators

Sahar Mosleh California State University San MarcosPage 20 "Shortcut" operators - C++ provides a series of shorthand operators for performing an operation with the same variable you intend to assign the result to - Instead of Try x= x+ y; x+= y; x= x* 2; x*= 2; - … and so on. - Feel free to use these!

Sahar Mosleh California State University San MarcosPage 21 Overloading Shortcuts - The reason I bring this up is that += is overloaded for strings as well - you can write: line += word1+ word2+ word3; - same meaning as line = line+ word1+ word2+ word3; - The others don't make sense for strings, but you may see them overloaded for other types - and as already stated possible to overload them yourself

Sahar Mosleh California State University San MarcosPage 22 String Member Functions - The string class provides a number of useful member functions - Object-Oriented-Programming (OOP) - recall that member functions of a class are functions which operate on objects of that class (really part of the object!) - sometimes called "Methods” - notation is: VariableName.FunctionName(...) - the function FunctionName operates on the object (string) VariableName - may have some other parameters as well (e.g. fin.open(…) for file streams)

Sahar Mosleh California State University San MarcosPage 23 String Member Functions - Substrings: - the string class provides the substr member function to extract substrings from a string - Specification: string str1, str2; str2= str1.substr( first, numchars); - str2 is assigned the substring of str1 starting at position first and containing numchars characters - if str1 does not have numchars chars after first, str2 just copies up to end of str1

Sahar Mosleh California State University San MarcosPage 24 String Member Functions - Substrings (continued) - Example: string line="This course is not that hard guys"; string line2, line3; line2 = line.substr(5,6); line3 = line.substr(15,8); cout << "line 2 is: \""<< line2 <<"\""<< endl; cout << "line 3 is: \"" << line3 << "\""<< endl; – Output: line 2 is: “course” line 3 is: “not that”

Sahar Mosleh California State University San MarcosPage 25 String Member Functions - Substring replacement - The substr function does not modify its object - If you want to change a substring, use the replace function - Specification: string str1, str2; str1.replace( first, numchars, str2); - Action: - replace chars in str1, starting at index first and extending numchars positions, with the string str2.

Sahar Mosleh California State University San MarcosPage 26 String Member Functions - Example string line="Let us now replace some text."; line.replace( 4, 10, "it snow. P"); cout << line << endl; - Output Let it snow. Place some text. - Note that "it snow. P" contains 10 chars and we replaced 10 chars. This is not always necessary

Sahar Mosleh California State University San MarcosPage 27 String Member Functions - Can replace substrings with shorter or longer substrings - the length of the string will change - Example: string line="Let us now replace some text."; cout << line.size() << “” ; line.replace(4, 19, "it snow"); cout << line << “ ” << line.size() << endl; – Output: 30 Let it snow text. 18

Sahar Mosleh California State University San MarcosPage 28 String Member Functions - Two other member functions closely related to replace are erase and insert. - these functions can be done with replace - more convenient and suggestive to use erase and insert when appropriate

Sahar Mosleh California State University San MarcosPage 29 String Member Functions - Erase: - Specification: string line; line.erase( start, numchars); - delete numchars chars starting at index start - functionally same as: line.replace( start, numchars, ""); - "" is the null string (length 0)

Sahar Mosleh California State University San MarcosPage 30 String Member Functions - Insert: - Specification: string line, instr; line.insert( start, instr); - insert string instr into line, starting at index start - don't overwrite any characters in line just shift to the right - functionally same as: line.replace( start, 0, instr); - replace 0 characters of line, starting at position start, with instr

Sahar Mosleh California State University San MarcosPage 31 String Member Functions - Examples: string line="Walking on the sun is hot"; line.erase(15,4); cout << line << endl; line.insert(15,"moon "); cout << line << endl; - Output: Walking on the is hot Walking on the moon is hot

Sahar Mosleh California State University San MarcosPage 32 String Search Functions - The string class also offers a very useful searching function: find - Specification: string line, pattern; int pos, x;... x = line.find( pattern, pos); - x will contain the first location of pattern within line starting at or after position pos or line.npos (a special constant) if pattern not found in line at or after position pos

Sahar Mosleh California State University San MarcosPage 33 String Search Functions - Example: string line=" This and that and more and less"; int p; p= line.find( "and",0); // search, start at pos'n 0 while (p != line.npos) { cout << "Found an \" and\" at index " << p << endl; // continue looking at location p+ 1 p= line.find("and", p+1); } Output: Found an “and” at index 6 Found an “and” at index 15 Found an “and” at index 24

Sahar Mosleh California State University San MarcosPage 34 -Makes Sure to Study all the examples for this lecture. -Specially, examples 10 and 11 are very important. Similar questions may appear in the labs, assignments and exams