String Objects: The string class library

Similar documents
C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

Object Oriented Programming COP3330 / CGS5409

LECTURE 15. String I/O and cstring library

Assignment 5: MyString COP3330 Fall 2017

Engineering Problem Solving with C++, Etter

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

Copyright 2003 Pearson Education, Inc. Slide 1

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

Full file at

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points.

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Chapter 10 Characters, Strings, and the string class

CSCE 110 PROGRAMMING FUNDAMENTALS

CS106X Handout 04 Autumn 2009 September 25 th, 2009 C++ Strings

Strings in C++ Dr. Ferdin Joe John Joseph Kamnoetvidya Science Academy

STRINGS AND STRINGBUILDERS. Spring 2019

COP Programming Assignment #7

CPE Summer 2015 Exam I (150 pts) June 18, 2015

CS106X Handout 04 Winter 2018 January 8 th, 2018 C++ Strings

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

In this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Objectives. In this chapter, you will:

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

Chapter 10: Character Testing. From Program Character Case Conversion 8/23/2014. Character Testing. Character Case Conversion

Chapter 10: Characters, C- Strings, and More About the string Class

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

8. Control statements

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Unit 14. Passing Arrays & C++ Strings

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

13 4 Understanding Character Strings

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

Chapter 2 Basic Elements of C++

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 10: Characters, C- Strings, and More About the string Class Character Testing

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Intermediate Programming, Spring 2017*

The C++ Language. Arizona State University 1

Unit 2: The string class

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

The string Class. Lecture 21 Sections 2.9, 3.9, Robb T. Koether. Wed, Oct 17, Hampden-Sydney College

String Variables and Output/Input. Adding Strings and Literals to Your Programming Skills and output/input formatting

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Chapter 9. Strings. 國立雲林科技大學資訊工程研究所張傳育 (Chuan Yu Chang ) 博士

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Introduction to string

Name Section: M/W T/TH Number Definition Matching (6 Points)

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Chapter 7: User-Defined Simple Data Types, Namespaces, and the string Type

B.V. Patel Institute of BMC & IT, UTU 2014

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

by Pearson Education, Inc. All Rights Reserved. 2

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

CS106B Handout #5 Winter January 9, 04

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

BITG 1113: Array (Part 2) LECTURE 9

Programming in Python

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

Name. CPTR246 Spring '17 (100 total points) Exam 2

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

(Refer Slide Time: 01:12)

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Separate Compilation Model

Sprite an animation manipulation language Language Reference Manual

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?


G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

Dodatak D Standardna string klasa

Data Types and Expressions. C# Programming: From Problem Analysis to Program Design 2nd Edition

LECTURE 02 INTRODUCTION TO C++

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

CSc Introduction to Computing

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Java Fall 2018 Margaret Reid-Miller

COP4020 Programming Assignment 1 - Spring 2011

CS2141 Software Development using C/C++ C++ Basics

Software Design & Programming I

Mobile App:IT. Methods & Classes

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Computer Programming

Dynamic arrays / C Strings

Transcription:

String Objects: The string class library Lecture 23 COP 3014 Spring 2017 March 7, 2017

C-strings vs. string objects In C++ (and C), there is no built-in string type Basic strings (C-strings) are implemented as arrays of type char that are terminated with the null character string literals (i.e. strings in double-quotes) are automatically stored this way Advantages of C-strings: Compile-time allocation and determination of size. This makes them more efficient, faster run-time when using them Simplest possible storage, conserves space Disadvantages of C-strings: Fixed size Primitive C arrays do not track their own size, so programmer has to be careful about boundaries The C-string library functions do not protect boundaries either! Less intuitive notation for such usage (library features)

string objects C++ allows the creation of objects, specified in class libraries Along with this comes the ability to create new versions of familiar operators Coupled with the notion of dynamic memory allocation (not yet studied in this course), objects can store variable amounts of information inside Therefore, a string class could allow the creation of string objects so that: The size of the stored string is variable and changeable Boundary issues are handled inside the class library More intuitive notations can be created One of the standard libraries in C++ is just such a class

The string class library The cstring library consists of functions for working on C-strings. This is a C library The library called string, which is part of the Standard Template Library in C++, contains a class called string Strings are declared as regular variables (not as arrays), and they support: the assignment operator = comparison operators ==,!=, etc the + operator for concatenation type conversions from c-strings to string objects a variety of other member functions To use this library, make sure to #include it: #include <string>

Declaring and initializing Declare like a regular variable, using the word string as the type: string firstname; string lastname string address; string s1; To initialize, you can use the assignment operator, and assign a string object to another, or a string literal to a string object: firstname = "Joe"; lastname = "Smith"; address = "123 Main St."; s1 = firstname; // s1 is now "Joe" also

Declaring and initializing And you can initialize on the same line as the declaration: string s2 = "How are you?"; string s3 = "I am fine."; string s4 = "The quick brown duck jumped over the lazy octopus"; You can also initialize on the declaration statement in this format: string fname("marvin"); string lname("dipwart"); string s2(s1); // s2 is created as a copy of s1

Comparing string objects You can compare the contents of string objects with the standard comparison operators: if (s1 == s2) cout << "The strings are the same"; if (s1 < s2) cout << "s1 comes first lexicograpically"; You can also mix and match with C-strings, as long as one of the operands is a string object: if (s1 == "Joe") cout << "The first student is Joe"; if (s2 > "apple") cout << "s2 comes after apple in the dictionary";

Comparing string objects The ordering on strings is a lexicographical ordering, which goes by ASCII values of the characters. So it s not exactly the same as alphabetical In the ASCII character set, upper case letters all come before the lower case letters. So, apple < apply apple > Apply apple > Zebra

Concatenation with the + operator The + operator is overloaded in this library to perform string concatenation. It takes two strings, concatenates them, and returns the result Example: string s1 = "Bat"; string s2 = "man"; string s3; s3 = s1 + s2; // s3 is now "Batman" You can also concatenate a C-string onto a string object: string s4 = s3 + " is cool"; // s4 is now "Batman is cool"

Concatenation with the + operator The += operator is also supported, for concatenation ON to the string on the left side: string t1 = "Bird"; string t2 = "Boogie"; t1 += "brain"; // t1 is now "Birdbrain" t1 += " "; t1 += t2; // t1 is now "Birdbrain Boogie"

Input and output The string library also includes versions of the insertion and extraction operators, for use with string objects The insertion operator is used as with any other variable, and it will print the contents of the string: string s1 = "Hello, world"; string s2 = "Goodbye, "; cout << s1; // prints "Hello, world" cout << s2 + " now";// prints "Goodbye, now" The extraction operator, like the one for c-strings, will skip leading white space, then read up to the next white space (i.e. one word only): string s3; cin >> s3; // will read one word

Input and Output To read more than one word, you can use a function called getline. This is similar to the getline function for c-strings, but the syntax is a little different. string addr; // string object getline(cin, addr); // reads up to newline, for string object getline(cin, addr,, ); // reads up to comma, for string object For the string object version of getline, the first parameter is the input stream (like cin), the second is the string object, and the third optional parameter is the delimeter. You don t need a size parameter.

The [] operator A string object stores the string internally as an array of characters, but it makes the notation easier, so that you don t have to declare it like an array However, sometimes we want to access individual letters or character positions in the string. The class supports the [] operator for this purpose Indexing starts at 0, just like with an array. Usage: string name[index]. This call will return a reference to the character at position index. This means it can be read and it can be changed through this operation

Examples string s1 = "Apple pie and ice cream"; cout << s1[0]; // prints A cout << s1[4]; // prints e s1[4] = y ; s1[8] = g ; cout << s1; // prints "Apply pig and ice cream"

string class member functions member functions are called through the dot-operator size() returns the length of the string length() returns the length of the string (same as size()) capacity() returns the current allocated size of the string object (allocation might be larger than current usage, which is the length) resize(x, CH) changes the string s allocated size to X. If X is bigger than the currently stored string, the extra space at the end is filled in with the character CH clear() delete the contents of the string. Reset it to an empty string empty() return true if the string is currently empty, false otherwise at(x) return the character at position X in the string. Similar to using the [] operator

More string functions Substrings substr(x, Y) returns a copy of the substring (i.e. portion of the original string) that starts at index X and is Y characters long substr(x) returns a copy of the substring, starting at index X of the original string and going to the end Examples string s1 = "Greetings, earthling"; string s2 = s1.substr(11,5); // s2 is now "earth" string s3 = s1.substr(4); // s2 is now "tings, earthling" Assign there are several functions called assign which are for assigning data to a string. There are versions with the same parameter lists as with the append functions, but these assign the string to the requested data, while append adds it to the end of an existing string

More string functions Append several versions. All of these append something onto the END of the original string (i.e. the calling object, before the dot-operator) append(str2) appends str2 (a string or a c-string) append(str2, Y) appends the first Y characters from str2 (a string or char array) append(str2, X, Y) appends Y characters from str2, starting at index X append(x, CH) appends X copies of the character CH Find multiple versions str.find(str2, X) returns the first position at or beyond position X where the string str2 is found inside of str str.find(ch, X) returns the first position at or beyond position X where the character CH is found in str

More string functions Compare multiple versions str1.compare(str2) performs a comparison, like the c-string function strcmp. A negative return means str1 comes first. Positive means str2 comes first. 0 means they are the same str1.compare(str2, X, Y) compares the portions of the strings that begin at index X and have length Y. Same return value interpretation as above Insert multiple versions str.insert(x, Y, CH) inserts the character CH into string str Y times, starting at position X str.insert(x, str2) inserts str2 (string object or char array) into str at position X