C String, Proper Type, and String Objects Andy Wang COP 4530: Data Structures, Algorithms, and Generic Programming.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
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.
Introduction to Programming Lecture 39. Copy Constructor.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 09 Strings, IDEs. METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 29, 2002.
Ch 8. Characters and Strings Timothy Budd 2 Characters and Literals Strings Char in C++ is normally an 8-bit quantity, whereas in Java it is a 16-bit.
Lecture 20 Arrays and Strings
Chapter Fourteen Strings Revisited. Strings A string is an array of characters A string is a pointer to a sequence of characters A string is a complete.
Array_strcpy void array_strcpy(char dest[], char src[]) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; }
Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.
Definition of Strings Generally speaking, a string is a sequence of characters c string c++ string class Examples: “hello”, “high school”, “H2O”. Typical.
. Plab – Tirgul 2 Const, C Strings. Pointers int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; ijx 1.
. Plab – Tirgul 8 I/O streams Example: string class.
COMP102 – Programming Fundamentals I LA2B (Mon 5-7pm) LA2E (Fri 3-5pm) LA2F (Fri 5-7pm) TA: Jackie Lo.
N-1 University of Washington Computer Programming I Lecture 19: Strings © 2000 UW CSE.
C strings (Reek, Ch. 9) 1CS 3090: Safety Critical Programming in C.
Programming Strings. COMP102 Prog. Fundamentals: Strings / Slide 2 Character Strings l A sequence of characters is often referred to as a character “string”.
Dynamic Memory for Class #include #ifndef STRCLASS_H_ #define STRCLASS_H_ class strclass { private: char *str; int len; static int num_strings; public:
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C-Strings Joe Meehean. C-style Strings String literals (e.g., “foo”) in C++ are stored as const char[] C-style strings characters (e.g., ‘f’) are stored.
Object Oriented Programming in C++ Chapter5 Operator Overloading.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Introduction to C programming
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.
Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
String Library Calls (Representative, not Exhaustive) Rudra Dutta CSC Spring 2007, Section 001.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
1 CSC241: Object Oriented Programming Lecture No 22.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
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.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Xuan Guo Review for the Final Exam Xuan Guo July 29 8:30AM – 10:30AM Classroom South 300 CSC
A Generic List Class and Linked Lists Andy Wang Data Structures, Algorithms, and Generic Programming.
String functions+ string I.Mona Alshehri. String Functions: Header file:#include Function: Int strlen(char s[n]) Description Calculates the length of.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Duke CPS 6. 1 arrays and strings: pointers and memory allocation l Why not rely solely on string and Vector classes? ä how are string and Vector implemented?
One-dimensional arrays and strings: Chapter 6, Slide 1 The concept of array - an extension of the basic model of memory:
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 5 1.
CS 1430: Programming in C++ 1. Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Operator Overloading Moshe Fresko Bar-Ilan University Object Oriented Programing
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
©Copyrights 2016 Eom, Hyeonsang All Rights Reserved Computer Programming Object Oriented Programming & C++ 1 st Lecture 엄현상 (Eom, Hyeonsang) Department.
Suyash Bhardwaj Dept. of Computer Science & Engineering Faculty of Engineering & Technology Gurukul Kangri University, Haridwar l1l1 UNIT 1 String Processing.
Yan Shi CS/SE 2630 Lecture Notes
Pointers and Dynamic Arrays
Strings: C-strings vs. Strings as Objects
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Overloading Operator MySting Example
Lecture 8 String 1. Concept of strings String and pointers
Object-Oriented Programming (OOP) Lecture No. 17
LinkedList Class.
Object Oriented Programming COP3330 / CGS5409
Strings: C-strings vs. Strings as Objects
Arrays and Pointers Reference: Chapter , 4.11 CMSC 202.
String in C++.
C++ Pointers and Strings
EECE.2160 ECE Application Programming
C++ Pointers and Strings
Destructors, Copy Constructors & Copy Assignment Operators
Destructors, Copy Constructors & Copy Assignment Operators
Presentation transcript:

C String, Proper Type, and String Objects Andy Wang COP 4530: Data Structures, Algorithms, and Generic Programming

Lecture Overview Goal –Design a string class that overcomes the disadvantages of C strings Roadmap –Critique of C strings –The need for proper type –String objects

In-Class Exercise Write a C function that copies one string to another. void strcpy(char *dest, char *src) { … }

Assumptions of C Strings Allocated memory char *str; str = malloc(sizeof(char)*11); Null termination str[10] = “\0” strcpy(str, “ ”);

What can go wrong? void strcpy(char *copy_cat, char *cat) { int j; for (j = 0; cat[j] != ‘\0’; j++) { copy_cat[j] = cat[j]; } copy_cat[j] = ‘\0’; } What if the string is not null terminated? What if the string is not allocated?

Other String Functions Still assume null-terminated strings Still assume allocated memory Security holes… –Internet worms –System break-ins

The Concept of Proper Type A proper type should be –Responsible for its own data Data protected from clients and other programs –Responsible for its own behavior Make behavior available to clients Implementation hidden from the public view –Responsible for its own existence Automatic memory management

C++ Class Objects Responsible for their own data –Protected or private data –Controlled access through public methods Responsible for their own behavior –Public methods Responsible for their own existence –Constructors/deconstructors

In-Class Exercise: String Class namespace rcl { class String { // friend… public: // … private: // … } // … }

String Class class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // string comparison function private: // data // helper methods } // equality and order comparison operators

Private Data char *str; unsigned int size; // equal to C strlen(); class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // String comparison function private: // data // helper methods } // equality and order comparison operators

Data Accessors unsigned int Size() const; unsigned int Length() const; char Element(unsigned int n) const; class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // String comparison function private: // data // helper methods } // equality and order comparison operators

Data Accessors unsigned int String::Size() const { return size; } unsigned int String::Length() const { // note: strlen takes char*; therefore, we need to implement an operator that converts String to char*. return strlen(*this); }

In-Class Exercise: Element Return the nth character of the String. Watch out for boundary cases. char String::Element(unsigned int n) const { … }

Element char String::Element(unsigned int n) const { char ch; if ((size == 0) || (n >= size)) { return ‘\0’; } else { return str[n]; }

String Comparison Function static int StrCmp(const String&, const String&) class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // String comparison function private: // data // helper methods } // equality and order comparison operators

StrCmp int String::StrCmp(const String& S1, const String& S2) { if ((S1.Size() == 0) && (S2.Size() == 0)) { return 0; } else if ((S1.Size() == 0) && (S2.Size() != 0)) { return –1; } else if ((S1.Size() != 0) && (S2.Size() == 0)) { return 1; } else { return (strcmp(S1.str, S2.str); }

Equality Operators int operator==(const String& S1, const String& S2); int operator!=(const String& S1, const String& S2); int operator<(const String& S1, const String& S2); int operator<=(const String& S1, const String& S2); int operator>=(const String& S1, const String& S2); int operator>(const String& S1, const String& S2); class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // String comparison function private: // data // helper methods } // equality and order comparison operators

Comparison Operators int operator==(const String& S1, const String& S2) { return (String::StrCmp(S1, S2) == 0); } int operator!=(const String& S1, const String& S2) { return (String::StrCmp(S1, S2) != 0); } int operator>(const String& S1, const String& S2) { return (String::StrCmp(S1, S2) > 0); }

Comparison Operators int operator>=(const String& S1, const String& S2) { return (String::StrCmp(S1, S2) >= 0); } int operator<(const String& S1, const String& S2) { return (String::StrCmp(S1, S2) < 0); } int operator<=(const String& S1, const String& S2) { return (String::StrCmp(S1, S2) <= 0); }

Helper Methods static void Error(const char*); static char* newstr(int n); static int xstrlen(const char*); static void xstrcpy(char *, const char*); void Clear(); void Clone(const String& S); class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // String comparison function private: // data // helper methods } // equality and order comparison operators

Error void String::Error(const char* msg) { cerr << “** String error: “ << msg << ‘\n’; exit(EXIT_FAILURE); }

In-Class Exercise: newstr It creates a new String of size n (C String with an array size of n + 1). void String::newstr(int n) { … }

newstr char *String::newstr(int n) { char *Cptr = 0; if (n >= 0) { Cptr = new char[n + 1]; if (Cptr == 0) { Error(“memory allocation failure”) } Cptr[n] = ‘\0’; } return Cptr; }

xstrlen int String::xstrlen(const char* s) { int len; if (s != 0) { // check for null pointer for (len = 0; s[len] != ‘\0’; ++len) { } } return len; }

xstrcpy void String::xstrcpy(char *dest, const char *src) if (src != 0) { // check for null pointer if (dest != 0) { // check for null pointer int j; for (j = 0; src[j] != ‘\0’; ++j) { dest[j] = src[j]; } dest[j] = ‘\0’; } else { Error(“xstrcpy: null destination”); }

In-Class Exercise: Clear If the String has storage allocated, delete it, and set the storage pointer and size to zero. void Clear() { … }

Clear void String::Clear() { if (str) { delete[] str; str = 0; size = 0; }

In-Class Exercise: Clone If makes a copy of the parameter S. void *String::Clone(const String& S) { … }

Clone void String::Clone(const String& S) { size = S.Size(); if (size > 0) { str = newstr(size); xstrcpy(str, S.str); } else { str = 0; }

Operators String &operator=(const String& S); char &operator[] (unsigned int I) const; operator const char* () const class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // String comparison function private: // data // helper methods } // equality and order comparison operators

Operator= String &String::operator=(const String& S) { if (this != &S) { Clear(); Clone(S); } return *this; }

Operator[] char& String::operator[] (unsigned int n) const { if ((size == 0) || (n > size)) { Error(“index out of range”); } return str[n]; }

Operator const char* String::operator const char* () const { return str; }

Builder Functions void Wrap(const char* Cptr); void GetLine(istream& inl); int SetSize(unsigned int sz, char fill); class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // String comparison function private: // data // helper methods } // equality and order comparison operators

Wrap void String::Wrap(const char* Cptr) { Clear(); if (Cptr) { size = xstrlen(Cptr); str = newstr(size); xstrcpy(str, Cptr); }

GetLine void String::GetLine(istream& is) { unsigned int curr_size = 0, buff_size = init_buff_size; char *buffer = new char[buff_size + 1]; for (char x = is.get(); ((x != ‘\n’) && (!is.eof()); x = is.get()) { if (curr_size == buff_size) { buff_size *= 2; char *newbuffer = new char[buff_size + 1]; // copy buffer to newbuffer delete[] buffer; buffer = newbuffer; } buffer[curr_size++] = x; } buffer[curr_size] = ‘\0’; Wrap(buffer); delete[] buffer; }

SetSize int String::SetSize(unsigned int sz, char fill) { if (sz != Size()) { char *newdata = newstr(sz); if (newdata == 0) return 0; unsigned int j; if (sz < Size()) { for (j = 0; j < sz; ++j) { newdata[j] = str[j]; } } else { for (j = 0; j < Size(); ++j) { newdata[j] = str[j]; } for (j = Size(); j < sz; ++j) { newdata[j] = fill; } delete[] str; str = newdata; size = sz; } return 1; }

Constructors/Destructors String(); explicit String(const char* Cptr); ~String(); String (const String &S); class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // String comparison function private: // data // helper methods } // equality and order comparison operators

Constructors / Deconstructors String::String() : str(0), size(0) {} String::String(const char *Cptr) : str(0), size(0) { Wrap(Cptr); } String::String(const String& S) { Clone(S); } String::~String() { if (str) delete[] str; }

I/O Operators friend ostream& operator<<(ostream& os, const String& S); friend istream& operator>>(istream& is, String S); class String { // friend iostream operators public: // constructors/destructors // operators // builders // data accessors (const) // String comparison function private: // data // helper methods } // equality and order comparison operators

Operator<< ostream& operator<<(ostream& os, const String& S) { os << S.str; return os; }

Operator>> istream& operator>>(istream &is, String &S) { unsigned int curr_size = 0; buff_size = init_buff_size; char x; // skip clear space char *buffer = String::newstr(buff_size); buffer[curr_size++] = x; for (x = is.peek(); (// x is not white space or eof); x = is.peek()) { if (curr_size == buff_size) { buff_size *= 2; char *newbuffer = String::newstr(buff_size); // copy buffer into newbuffer delete[] buffer; buffer = newbuffer; } buffer[curr_size++] = x; is.get(); } buffer[curr_size] = ‘\0’; S.Wrap(buffer); delete[] buffer; return is; }