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

Similar documents
Chapter 3 Objects, Types, and Values

Types, Values, Variables & Assignment. EECS 211 Winter 2018

Chapter 3 Objects, types, and values. Bjarne Stroustrup

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Intermediate Programming, Spring 2017*

Programmazione. Prof. Marco Bertini

Chapter 15 - C++ As A "Better C"

CS242 COMPUTER PROGRAMMING

Introduction to C++ Systems Programming

Engineering Problem Solving with C++, Etter

CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors

Computer Science II Lecture 2 Strings, Vectors and Recursion

Programming with C++ as a Second Language

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

Introduction to C++ Introduction to C++ 1

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

Exercise 1.1 Hello world

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

LECTURE 15. String I/O and cstring library

Lecture 3 The character, string data Types Files

Why C++? C vs. C Design goals of C++ C vs. C++ - 2

CSc Introduc/on to Compu/ng. Lecture 17 Edgardo Molina Fall 2011 City College of New York

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

PHY4321 Summary Notes

LECTURE 02 INTRODUCTION TO C++

Introduction to C++ (Extensions to C)

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors

Instantiation of Template class

AN OVERVIEW OF C++ 1

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Objectives. In this chapter, you will:

CSCI 1061U Programming Workshop 2. C++ Basics

Intermediate Programming, Spring 2017*

Short Notes of CS201

Chapter 2 C++ Fundamentals

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

CS201 - Introduction to Programming Glossary By

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

Fast Introduction to Object Oriented Programming and C++

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

Dodatak D Standardna string klasa

This watermark does not appear in the registered version - Slide 1

QUIZ. What is wrong with this code that uses default arguments?

CS

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

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

Working with Batches of Data

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

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

Class string and String Stream Processing Pearson Education, Inc. All rights reserved.

Streams. Ali Malik

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Definition Matching (10 Points)

CS302 - Data Structures using C++

Differentiate Between Keywords and Identifiers

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Assignment operator string class c++ Assignment operator string class c++.zip

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

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

Chapter 1 Introduction to Computers and C++ Programming

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

Chapter 2 Basic Elements of C++

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Arrays. Week 4. Assylbek Jumagaliyev

Object Oriented Design

G52CPP C++ Programming Lecture 18

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

CS3157: Advanced Programming. Outline

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

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

Chapter 10 Characters, Strings, and the string class

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Object Oriented Programming COP3330 / CGS5409

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Introduction to Programming

CSCE 110 PROGRAMMING FUNDAMENTALS

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };

by Pearson Education, Inc. All Rights Reserved. 2

Tutorial-2a: First steps with C++ programming

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

Lecture 5 Files and Streams

C++ Code Structure. Cooperating with the Compiler

C++ is Evolving. std::array

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

Chapter 2: Basic Elements of C++

Computer Programming C++ Classes and Objects 6 th Lecture

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

Assignment 5: MyString COP3330 Fall 2017

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017

Lecture 7. Log into Linux New documents posted to course webpage

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

G52CPP C++ Programming Lecture 17

UEE1302 (1102) F10: Introduction to Computers and Programming

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:

CSE 303: Concepts and Tools for Software Development

Transcription:

Working with Strings Lecture 2 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/spring_2015/csc1254.html

Abstract This lecture will look at strings. What are strings? How can we input/output strings? How can we manipulate strings? What functionality is provided by the std::string type? 2

C++ Libraries Groups related operations Header file provides function prototypes and usage comments Compiled library contains implementation C++ Standard Libraries E.g. string, iostream, fstream #include <foo> Terse lowercase names: cout, getline, substr 3

String Input Given the following interaction: Please enter your name: John We would like to print: Hello John! 4

String Input // Ask a persons name, greet the person #include <iostream> #include <string> int main() { // ask for the persons name std::cout << "Please enter your first name: "; // read the name std::string first_name; std::cin >> first_name; // define 'first_name' // read into 'first_name' } // write a greating std::cout << "Hello, " << first_name << std::endl; return 0; 5

String Input Place to put input into: variable Variables are objects which have a name (first_name) Objects are part of the computer memory with an associated type (std::string) std::string Part of namespace std #include <string> Powerful data type conveniently enabling string manipulations 6

String Input Variable definition: std::string name; Local variable, is destroyed at end of block Type defines the available operations and interface exposed by the object Initialization, here: empty (or null) string String input using operator >> from std::cin Discards leading whitespace Stops at whitespace Input/output buffering occurs flushing is performed: buffer full, input, explicit request 7

Names A name in a C++ program Starts with a letter, contains letters, digits, and underscores (only) x, number_of_elements, Fourier_transform, z2 Not names: 12x time$to$market main line Do not start names with underscores: _foo those are reserved for implementation and system entities Users can't define names that are taken as keywords E.g.: int return while double 8

Names Choose meaningful names Abbreviations and acronyms can confuse people mtbf, TLA, myw, nbv, wtf Short names can be meaningful when used conventionally: x is a local variable i is a loop index Don't use overly long names Ok: partial_sum element_count staple_partition Too long: the_number_of_elements remaining_free_slots_in_the_symbol_table 9

Framing a Name Given the following interaction: Please enter your name: John We would like to print: ******************* * * * Hello John! * * * ******************* 10

Framing a Name // Ask a persons name, greet the person #include <iostream> #include <string> int main() { std::cout << "Please enter your first name: "; std::string first_name; std::cin >> first_name; // ask for the persons name // define 'first_name' // read into 'first_name' } std::string const greeting = "Hello, " + first_name + "!"; // build the message we intend to write std::string const spaces(greeting.size(), ' '); // build the second and fourth string std::string const second = "* " + spaces + " *"; std::string const first(second.size(), '*'); // build the first and fifth lines std::cout << first << std::endl; // write all std::cout << second << std::endl; std::cout << "* " + greeting + " *" << std::endl; std::cout << second << std::endl; std::cout << first << std::endl; return 0; 11

Framing a Name Variable definition Initialization Important! Use operator + for concatenation Custom operators do not change precedence, associativity, or number of arguments Constness (keyword const) Variable will not be changed Requires initialization May allows for more optimizations Expresses intention to the compiler 12

Framing a Name Initializing using special constructor std::string spaces(greeting.size(), ' '); Number of characters and character literal (' ') Quoting similar to string literals ('\t', etc.) 13

C++ std::string Models a sequence of characters std::string is defined as class (user defined) type Simple operations Member function size() returns number of chars operator[] to access individual characters C++ strings are mutable Operators on strings operator= assigns, makes new copy Compare with relational operators: <, <=, ==, >=, > Lexicographical ordering operator+ concatenates 14

C++ std::string #include <iostream> #include <string> // std::cout, std::endl // std::string int main() { std::string s, t = "hello"; s = t; // s == "hello" std::cout << "Length: " << s.size() << std::endl; t[0] = 'j'; // t == "jello" s = s + ' '; // s == "hello " s += t; } std::cout << s << std::endl; return 0; // prints: 'hello jello' 15

C++ std::string #include <iostream> #include <string> #include <cctype> #include <algorithm> // std::cout, std::endl // std::string // std::toupper // std::transform int main() { std::string s; s = "csc1254/1"; // converts to upper case std::transform(std::begin(s), std::end(s), std::begin(s), std::toupper); } std::cout << s << std::endl; return 0; // prints: CSC1254/1 16

C++ std::string #include <iostream> #include <string> #include <algorithm> // std::cout, std::endl // std::string // std::sort int main() { std::string s; s = "hello John"; // sort all characters of the string std::sort(std::begin(s), std::end(s)); } std::cout << s << std::endl; return 0; // prints: ' Jehhllnoo' 17

C++ std::string member functions Invoke member functions as: str.function(args) Sample member functions: Return index of first occurrence or std::string::npos int find(char c, int pos) int find(std::string pattern, int pos) Return new string, copies len characters starting at pos std::string substr(int pos, int len) Changes string, inserts txt at pos void insert(int pos, std::string txt) Changes string, removes len characters starting at pos void erase(int pos, int len) Changes string, removes len characters starting at pos, inserts txt void replace(int pos, int len, std::string txt) 18

More String Details IO is using operator>> and operator<< os << s: output s to stream os without formatting changes evaluates to os is >> s: input s from stream is with whitespace handling evaluates to is Ways to initialize: std::string hello = "hello"; std::string stars(10, '*'); std::string name; 19

C++ strings vs. C strings C++ inherits legacy of old-style C string String literals are actually C strings (pointer to array of null terminated characters) Converting C string to C++ string Happens automatically in most cases Can be forced: std::string("abc") Converting C++ string to C string Using member function s.c_str() Why do we care Some older functionality requires use of C strings C strings are not compatible with concatenation 20

C++ strings vs. C strings Concatenation pitfalls If one operand is a C++ string, all is good std::string str = "Hello "; str = str + "John"; str = str + '!'; If both operands are C strings/characters, bad times "abc" + "def"; "abc" + 'd'; // won't compile // will compile, but do wrong // thing Can force conversion if needed std::string("abc") + 'd'; 21