Working with Strings Lecture 2 Hartmut Kaiser

Slides:



Advertisements
Similar presentations
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Advertisements

CS 6301 Lecture 2: First Program1. CS Topics of this lecture Introduce first program  Explore inputs and outputs of a program Arithmetic using.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 3 Objects, Types, and Values Hartmut Kaiser
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 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Standard library types Practical session # 3 Software Engineering
Basic Elements of C++ Chapter 2.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
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.
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.
Working with Strings Lecture 2 Hartmut Kaiser
Chapter 1 Working with strings. Objectives Understand simple programs using character strings and the string library. Get acquainted with declarations,
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Chapter 10. Characters, Strings and the string class Csc 125 Introduction to C++ Fall 2005.
1 C++ Syntax and Semantics, and the Program Development Process.
C++ Programming: Basic Elements of C++.
Looping and Counting Lecture 3 Hartmut Kaiser
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
1 A simple C++ program // ======================================================= // File:helloworld.cpp // Author:Vana Doufexi // Date:1/4/2006 // Description:Displays.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
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.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Chapter 9 Strings. Learning Objectives An Array Type for Strings – C-Strings Character Manipulation Tools – Character I/O – get, put member functions.
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.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Lecture 2 Variables, Types, Operators Sampath Jayarathna Cal Poly Pomona Based on slides created by Bjarne Stroustrup & Tony Gaddis CS 128 Introduction.
Chapter 15 - C++ As A "Better C"
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ (Extensions to C)
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Topic Pre-processor cout To output a message.
Chapter 1: Introduction to computers and C++ Programming
Chapter 2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
ANNOUNCEMENT The missed lecture will be made up this Monday evening in the Tech PC classroom (MG51). A tentative time interval is 6:30-8:00. The exact.
Chapter 3 Objects, types, and values
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Strings (part 2) Dr. Xiao Qin Auburn.
Chapter 9 Strings Copyright © 2016 Pearson, Inc. All rights reserved.
Introduction to C++ Systems Programming.
Basic Elements of C++.
Working with Strings Lecture 2 Hartmut Kaiser
Characters, C-Strings, and More About the string Class
Chapter 3 Objects, Types, and Values
Standard Version of Starting Out with C++, 4th Edition
Chapter 2 part #3 C++ Input / Output
Basic Elements of C++ Chapter 2.
Chapter 3 Objects, types, and values
C++ STRINGS string is part of the Standard C++ Library
Learning Objectives String Class.
Wednesday 09/23/13.
Introduction to C++ Programming
Chapter 9 Strings Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Lecture 2 Variables, Types, Operators
Standard Version of Starting Out with C++, 4th Edition
Lecture 2 Fall 2011 September 13-15, 2011 Ghufran Ahmed
Chapter 2 part #3 C++ Input / Output
Today’s Objectives 28-Jun-2006 Announcements
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

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

CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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?

C++ Libraries Groups related operations C++ Standard Libraries CSC1254, Fall 2011, Strings 8/25/2011, Lecture 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

String Input Given the following interaction: We would like to print: CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 String Input Given the following interaction: Please enter your name: John We would like to print: Hello John!

CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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; // define 'first_name' std::cin >> first_name; // read into 'first_name' // write a greating std::cout << "Hello, " << first_name << std::endl; return 0; }

String Input Place to put input into: variable CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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>

String Input Variable definition: std::string name; CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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

Names A name in a C++ program CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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

Names Choose meaningful names CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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

Framing a Name Given the following interaction: CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 Framing a Name Given the following interaction: Please enter your name: John We would like to print: ******************* * * * Hello John! *

CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 Framing a Name // Ask a persons name, greet the person #include <iostream> #include <string> int main() { std::cout << "Please enter your first name: "; // ask for the persons name std::string first_name; // define 'first_name' std::cin >> 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 << first << std::endl; return 0; }

Framing a Name Variable definition Initialization CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 Framing a Name Variable definition Initialization Important! Use operator + for concatenation Custom operators do not change precedence, associativity, or number of arguments Constness Variable will not be changed Requires initialization

Framing a Name Initializing using special constructor CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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.)

C++ std::string Models a sequence of characters CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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

CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 C++ std::string #include <iostream> // std::cout, std::endl #include <string> // 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; // prints: 'hello jello' return 0; }

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

CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 C++ std::string #include <iostream> // std::cout, std::endl #include <string> // std::string #include <algorithm> // std::sort int main() { std::string s; s = "hello John"; std::sort(s.begin(), s.end()); // sort all characters of the string std::cout << s << std::endl; // prints: ' ehhllooJ' return 0; }

C++ std::string member functions CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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)

More String Details IO is using operator>> and operator<< CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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;

C++ strings vs. C strings CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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

C++ strings vs. C strings CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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"; // won't compile "abc" + 'd'; // will compile, but do wrong // thing Can force conversion if needed std::string("abc") + 'd';