C++ standard strings. Standard library of C++ language STL STL (The main part of standard library of C++ language) Stream classes Stream classes String.

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

EC-111 Algorithms & Computing Lecture #11 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
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.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Chapter 10.
Today’s Class Class string –The basics –Assignment –Concatenation –Compare & swap –Find –Conversion to C-style char * strings –Iterators.
 2006 Pearson Education, Inc. All rights reserved Class string and String Stream Processing.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
The Standard String Class Is actually a template: –typedef basic_string string This means you can have strings of things other than chars.
 2006 Pearson Education, Inc. All rights reserved Class string and String Stream Processing.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 12 More.
Operator Overloading in C++
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Data Structures Using C++ 2E
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.
Chapter 6 One-Dimensional Arrays ELEC 206 Computer Tools for Electrical Engineering.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
C++ String Class. Outline  String Initialization  Basic Operations  Comparisons  Substrings  Swapping Strings  String Size  Finding Strings and.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
File IO and command line input CSE 2451 Rong Shi.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
String Class. C-style and C++ string Classes C-style strings, called C-strings, consist of characters stored in an array ( we’ll look at them later) C++
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 15 - Class string and String Stream Processing Outline 15.1 Introduction 15.2 string Assignment.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
Chapter 16 C++ Strings By C. Shing ITEC Dept Radford University.
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
STL string class Programming Team 2/15/2006. string constructors string() = empty string string(int l, char ch) = string of length l, of repeated ch string(char*
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Strings, and the string Class. C-Strings C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character The C-string.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
Strings.
2008YeungNam Univ. SE Lab. 1  I n n amespace std : t ypedef basic_string string ; Type wchar_t for 16bit UNICODE. A. String near-containers  I.
CS212: Object Oriented Analysis and Design
Strings CSCI 112: Programming in C.
Operator Overloading; String and Array Objects
Class string and String Stream Processing: A Deeper Look
Standard Input/Output Streams
Standard Input/Output Streams
C++ STRINGS string is part of the Standard C++ Library
Operator Overloading; String and Array Objects
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Operator Overloading; String and Array Objects
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,
Class string and String Stream Processing
Today’s Objectives 28-Jun-2006 Announcements
Chapter 15 - Class string and String Stream Processing
character manipulation
A dictionary lookup mechanism
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

C++ standard strings

Standard library of C++ language STL STL (The main part of standard library of C++ language) Stream classes Stream classes String classes String classes (library defined within std namespace)

String class class representing ASCII strings class representing ASCII strings from template basic_string<> from template basic_string<> there is also wstring for alphabets like unicode there is also wstring for alphabets like unicode not an ASCIIZ string (char *) not an ASCIIZ string (char *) interface allows building expressions using: strings, C strings and chars interface allows building expressions using: strings, C strings and chars there is a conversion to sting class except for single char there is a conversion to sting class except for single char there is a constructor: string s(1, ‘c’); there is a constructor: string s(1, ‘c’); no automatic conversion from string class no automatic conversion from string class

String class Designed to behave like fundamental type... Designed to behave like fundamental type... internal memory management internal memory management stream operators stream operators... however with many extra methods... however with many extra methods like STL container (eg. vector) like STL container (eg. vector)

String class usage example Generating temporary names (string1.cpp) Generating temporary names (string1.cpp) string1.exe name.txt justname dot. moment.tmp name.txt => name.tmp justname => justname.tmp dot. => dot.tmp moment.tmp => moment.xxx string::size_type is type of index, use it, not an integer string::size_type is type of index, use it, not an integer string::npos denotes not a valid position (actually equals -1) string::npos denotes not a valid position (actually equals -1) similar to end iterator, however it is a value similar to end iterator, however it is a value as a result of string methods it means: “not found” as a result of string methods it means: “not found” as an argument of string methods it means: “all/remaining characters” as an argument of string methods it means: “all/remaining characters”

String class usage example Scrambling words (string2.cpp) Scrambling words (string2.cpp) input:Hello world! input:Hello world! output:olleH !dlrow output:olleH !dlrow now, guess the input input ;-) now, guess the input input ;-) output:gnirtS ssalc egasu elpmaxe output:gnirtS ssalc egasu elpmaxe getline(stream, string) getline(stream, string) inputs whole line, including and discarding EOL inputs whole line, including and discarding EOL returns false after EOF returns false after EOF third argument is a line delimeter, defaults to ‘\n’ third argument is a line delimeter, defaults to ‘\n’ access to string elements access to string elements operator[] – fast, no range checks operator[] – fast, no range checks method at() – slow due to checking of ranges method at() – slow due to checking of ranges size() – for all STL containers, length() – traditionally for strings size() – for all STL containers, length() – traditionally for strings nobody is perfect: sizeof() does not work like for fundamental type nobody is perfect: sizeof() does not work like for fundamental type

converting string to char * no automatic conversion no automatic conversion no ‘\0’ no ‘\0’ why no automatic conversion ??? why no automatic conversion ??? string::c_str() string::c_str() creates C ASCIIZ string, creates C ASCIIZ string, returns pointer valid until next call to nonstatic method or operator of string returns pointer valid until next call to nonstatic method or operator of string string::data() string::data() returns pointer to array of chars contained in string, no trailing ‘\0’ returns pointer to array of chars contained in string, no trailing ‘\0’ valid as c_str result valid as c_str result string::copy(char * const dest, int number, int staridx) string::copy(char * const dest, int number, int staridx) if number>length()-startidx copies length()-startidx characters if number>length()-startidx copies length()-startidx characters does not append ‘\0’ does not append ‘\0’

string length size() or length() size() or length() return current length return current length max_size() max_size() returns theoretical maximum size returns theoretical maximum size size greater than max_size is consiedered to be an error size greater than max_size is consiedered to be an error capacity() capacity() returns string size attainable without reallocation returns string size attainable without reallocation up to this size references, pointers (and iterators) continue to be valid up to this size references, pointers (and iterators) continue to be valid use reserve() method to increase capacity use reserve() method to increase capacity

const string & operator[] as opposed to non const operator [] and to at() as opposed to non const operator [] and to at() returns char instead of char& returns char instead of char& returns ‘\0’ when called: returns ‘\0’ when called: const string cs(“const”); char c = cs[cs.length()];

string methods boolean comparison operators:, >= boolean comparison operators:, >= integer result comparison string::compare() integer result comparison string::compare() assignment operator = assignment operator = works also for chars works also for chars overloaded assign() method overloaded assign() method when single argument is not enough when single argument is not enough string s, t; s.assign(„The”, 5);// ‘T’ ‘h’ ‘e’ ‘\0’ ‘\0’ t.assign(s,1,std::string::npos); // ‘h’ ‘e’

string methods std:swap() std:swap() quickly exchanges contents of two strings quickly exchanges contents of two strings emptying string emptying string string s; s=„”; s.empty();s.erase();

string methods inserting characters at the back inserting characters at the back string s(„Hello”); s+=‘ ’; s.append(„world”); // many overloaded variants, // eg. like assign s.push_back(‘!’); inserting characters inside the string inserting characters inside the string string s(„world!”); // s.insert(0, ‘ ‘);// no char argument s.insert(0, „Hello „);// specify index of character, before // which we insert

string methods replacing characters in the string replacing characters in the string string s(„Happy Easter!”); s.replace(6, 5, „New Yea”); // start index // number of chars // replacement (may be of different length) string::erase() for erasing fragments of the string string::erase() for erasing fragments of the string overloaded for either single char or start index and length overloaded for either single char or start index and length string::substr() returns substring string::substr() returns substring args: start index, number of chars (defaults to string::npos) args: start index, number of chars (defaults to string::npos)

string methods concatenating strings concatenating strings simply use the string::operator+() simply use the string::operator+() works also for char * and char works also for char * and char I/O operators > I/O operators > << outputs string according to formatting defined for the string << outputs string according to formatting defined for the string >> inputs >> inputs by default skips leading white spaces by default skips leading white spaces by default reads single word (stops at first white space) by default reads single word (stops at first white space) obeys skipws() obeys skipws() obeys setting of width() for the stream obeys setting of width() for the stream use global getline() for inputing whole lines use global getline() for inputing whole lines

string methods searching in strings searching in strings // searching for chars, strings and one of chars (not)contained in string // many overloaded variants of (first arg is always the searched text): find() // find first find() // find first rfind() // find last rfind() // find last find_first_of() // find first occurence of one of chars find_first_of() // find first occurence of one of chars find_last_of() // find last occurence of one of chars find_last_of() // find last occurence of one of chars find_first_not_of() // find first occurence of find_first_not_of() // find first occurence of // char different than argument // char different than argument find_last_not_of() // find last occurence of find_last_not_of() // find last occurence of // char different than argument (string2.cpp)

string as STL container string::iterator string::begin(); string::iterator string::begin(); string::iterator string::end(); string::iterator string::end(); the iterators may be used by STL algorithms (as vector iterators) the iterators may be used by STL algorithms (as vector iterators) they are valid as long as no nonstatic method or operator gets called they are valid as long as no nonstatic method or operator gets called there is also string::const_iterator there is also string::const_iterator iteators may be used for overloaded methods like: append(), assign(), insert(), erase(), replace() iteators may be used for overloaded methods like: append(), assign(), insert(), erase(), replace() (iter1.cpp iter2.cpp iter3.cpp)