Problems With Character Arrays

Slides:



Advertisements
Similar presentations
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.
Advertisements

1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
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.
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.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
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.
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.
String Constructors string str; // creates an empty //string string str(“abc”); // creates a string // from a C-string string str(aString); // creates.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Topics 1.File Basics 2.Output Formatting 3.Passing File Stream Objects to Functions 4.More Detailed Error Testing 5.Member Functions for Reading and 6.Writing.
Chapter 5 I/O Streams as an Introduction to Objects and Classes Goals:Goals: To determine how to use external files for input and output To determine.
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.
File I/O in C++ II. Open() function Open() is a member function in each classes ( fstream, ifstream, ofstream) Void fstream :: open ( const char *filename,
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
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.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
Chapter 8CS 140 Using The C++ Standard string Class #include #include using namespace std; void main() { string firstName = "Fred"; string lastName =
1 What is a Named Constant? A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed.
Data Types Storage Size Domain of all possible values Operations 1.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
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.
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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
ifstreams and ofstreams
Chapter Topics The Basics of a C++ Program Data Types
Chapter 8 (Part 3) Library Classes for Strings (P.405)
CS Computer Science IA: Procedural Programming
Lecture 9 Files, Pointers
Basic Elements of C++.
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists File I/O Dr. Xiao Qin Auburn University.
Engineering Problem Solving with C++, Etter
Multi-dimensional Array
Parallel Arrays Parallel array =>Two or more arrays with the same number of elements used for storing related information about a collection of data. Example:
Quiz Next Monday.
Basic Elements of C++ Chapter 2.
CS 1430: Programming in C++.
Pointer Data Type and Pointer Variables
Chapter 9 One-Dimensional Arrays
String class and its objects
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
File I/O in C++ I.
Engineering Problem Solving with C++, Etter
CS150 Introduction to Computer Science 1
Life is Full of Alternatives
CS150 Introduction to Computer Science 1
Statements and flow control
CHAPTER 4 File Processing.
Reading from and Writing to Files
CS150 Introduction to Computer Science 1
Using string type variables
(Dreaded) Quiz 2 Next Monday.
ifstreams and ofstreams
Pointer Data Type and Pointer Variables
Today’s Objectives 28-Jun-2006 Announcements
Programming Strings.
File I/O in C++ II.
Chapter 8 (Part 3) Library Classes for Strings (P.405)
File I/O in C++ I.
Reading from and Writing to Files
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

Problems With Character Arrays Numerous problems exist when we use traditional character arrays in C++: Wouldn’t it be nice if we could assign a character array a new value? Wouldn’t it be nice to be able to concatenate two character arrays? Wouldn’t it be nice to be able to retrieve a particular substring? Wouldn’t it be nice to be able to insert and remove whole substrings? Well, all of this and much, much more is possible with the new string class, made possible with a simple #include <string> preprocessing statement! Savitch - Chapter 11 CS 140

Using The C++ Standard string Class #include <iostream> #include <string> using namespace std; void main() { string firstName = "Fred"; string lastName = "Flintstone"; string fullName = firstName + ' ' + lastName; cout << fullName << endl << endl; fullName = "Wilma"; fullName += ' '; fullName += lastName; fullName.replace(0, 5, "Ms."); cout << fullName << endl; fullName.replace(4, 10, "Rubble"); fullName.insert(4, "Betty "); fullName[1] = 'r'; fullName.replace(5, 3, "arne"); return; } Notice it’s not cstring! Assignment statements, addition operators, output operators Additive assignment operators Member functions insert and replace Subscript operator Savitch - Chapter 11 CS 140

Substrings and Size Adjustment with strings #include <iostream> #include <string> using namespace std; void main() { string name("Scooby Doo"); cout << name << endl << endl; string middle = name.substr(1,5); cout << middle << endl; middle.at(0) = name.at(7); cout << middle << endl; for (int i = 1; i <= 16; i++) { name.insert(7, middle + ' '); cout << name << endl; } cout << endl; return; at member function substr member function string dynamically adjusts its size to accommodate new insertions! Savitch - Chapter 11 CS 140

Lexicographical Ordering of strings Arrays of type string are legal! #include <iostream> #include <string> using namespace std; void bubbleSort(string list[], int size); void main() { string quests[5] = {"jonny","Hadji","Race","bENTON","bandit"}; bubbleSort(quests, 5); for (int i = 0; i <= 4; i++) cout << quests[i] << endl; cout << endl; return; } Arrays of type string are legal! void bubbleSort(string list[], int size) { bool swapped = true; int lastIndex = size - 1; string tempString; while ((swapped) && (lastIndex > 0)) swapped = false; for (int i = 0; i < lastIndex; i++) if (list[i] > list[i+1]) tempString = list[i]; list[i] = list[i+1]; list[i+1] = tempString; swapped = true; } lastIndex--; <, >, <=, >=, ==, and != are all defined for class string, but they use a “lexicographical” ordering! Savitch - Chapter 11 CS 140

Comparing Parts of strings #include <iostream> #include <string> using namespace std; int IbeforeEmistakes(string wd); int EbeforeImistakes(string wd); void main() { string word; int i; cout << "Enter a word (enter 'quit' to exit): "; cin >> word; while (word != "quit") for (i = 1; i <= IbeforeEmistakes(word); i++) cout << "I BEFORE E EXCEPT AFTER C!" << endl; for (i = 1; i <= EbeforeImistakes(word); i++) cout << "E BEFORE I ONLY AFTER C!" << endl; cout << endl; cout << "Enter another word (enter 'quit' to exit): "; } return; string parameters can be passed by value! string values can be input! Savitch - Chapter 11 CS 140

Comparing Parts of strings (Continued) int IbeforeEmistakes(string wd) { int mistakeCount = 0; int index = wd.find("ie"); while (index >= 0) if ((index > 0) && (wd.find_first_of("Cc",index-1) == index-1)) mistakeCount++; index = wd.find("ie", index+2); } return mistakeCount; int EbeforeImistakes(string wd) int index = wd.find("ei"); if (index == 0) else if ((index > 0) && (wd.find_first_of("Cc",index-1) != index-1)) index = wd.find("ei", index+2); Finds the first index where the parameterized substring begins (returns -1 if it doesn’t occur)! Finds the first index where any character in the parameterized substring occurs, starting at the parameterized position (returns -1 if none of the characters occur from the parameterized position on)! Finds the first index where the parameterized substring begins starting at the parameterized position (returns -1 if it doesn’t occur from the parameterized position on)! Savitch - Chapter 11 CS 140

Comparing Parts of strings (Continued) Savitch - Chapter 11 CS 140

Storage Allocation for a string length and size are identical #include <iostream> #include <string> using namespace std; void main() { string firstWord = "Chapter One: The Beginning"; string secondWord = "Page 1"; cout << firstWord.size() << ' ' << firstWord.length() << ' ' << firstWord.max_size() << ' ' << firstWord.capacity() << endl; cout << firstWord << ' ' << secondWord << endl << endl; firstWord.resize(11); firstWord.resize(26); firstWord.resize(41,'*'); return; } length and size are identical max_size is the most the system can handle for one string; capacity is the current memory devoted to the string in question Savitch - Chapter 11 CS 140

Using strings to store filenames #include <iostream> #include <fstream> #include <string> using namespace std; void main() { string filename = "horribleSciFi.txt"; ofstream outfile; outfile.open(filename.c_str()); outfile << "Wesley Crusher\nJar Jar Binks\nNeelix\nEwoks\n" << "Rick Berman & Brannan Braga\n\n"; outfile.close(); } The c_str() function translates the string into a cstring. Wesley Crusher Jar Jar Binks Neelix Ewoks Rick Berman & Brannan Braga Final contents of ‘horribleSciFi.txt’. Savitch - Chapter 11 CS 140