Copyright  Hannu Laine C++-programming Part 5 Strings.

Slides:



Advertisements
Similar presentations
Starting Out with C++, 3 rd Edition 1 Chapter 10 – Characters, Strings, and the string Class.
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.
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
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.
Character String Manipulation. Overview Character string functions sscanf() function sprintf() function.
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.
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
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.
Character and String definitions, algorithms, library functions Characters and Strings.
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Chapter 7: User-Defined Simple Data Types, Namespaces, and the string Type.
Objectives In this chapter, you will:
C Strings. The char Data Type for Storing Characters The char data type can is used to declare a variable that can hold a single character. Examples:
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Chapter 10.
. 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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
C++ data types. Structs vs. Classes C++ Classes.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
C-strings Array with base type char One character per indexed variable
Week 7 – String. Outline Passing Array to Function Print the Array How Arrays are passed in a function call Introduction to Strings String Type Character.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
STRINGS & STRING HANDLING FUNCTIONS STRINGS & STRING HANDLING FUNCTIONS.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
Instructor - C. BoyleFall Semester
EGR 2261 Unit 9 Strings and C-Strings  Read Malik, pages in Chapter 7, and pages in Chapter 8.  Homework #9 and Lab #9 due next week.
C++ PROGRAMMING: PROGRAM DESIGN INCLUDING DATA STRUCTURES, FIFTH EDITION Chapter 10: Strings and string type.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
FLEX Fast Lexical Analyzer EECS Introduction Flex is a lexical analysis (scanner) generator. Flex is provided with a user input file or Standard.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
COP 3530 Data Structures & Algorithms Discussion Session 3.
11 Introduction to Object Oriented Programming (Continued) Cats.
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.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
Characters and Strings
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
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.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
KWIC example The KWIC [key word in context] system accepts an ordered set of lines; each line is an ordered set of words, and each word is an ordered set.
Pointers and Dynamic Arrays
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Class: Special Topics Copy Constructors Static members Friends this
C Stuff CS 2308.
More About Data Types & Functions
Arrays and Pointers Reference: Chapter , 4.11 CMSC 202.
Chapter 9 Introduction To Classes
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
String Class.
C++ data types.
cout << str1;  pear
Presentation transcript:

Copyright  Hannu Laine C++-programming Part 5 Strings

HL1 In C-language a character array with terminating zero is used as a string. C-library contains many string manipulation functions (string.h). There are many disadvantages in C-like strings: They can not be assigned with assignment operator. They can not be compared wit comparison operators. They cannot expand automatically, to mention some of the drawbacks. Now when we have learned basics of classes, we would be able to define a class string for example in the following way and implement its operation functions: class string { public: string(const char *string0=“”); string operator+(const string &s2) const; const string &operator=(const string &right); //and many other operators and member // functions private: char *c_string; }; But it is not necessary to implement it ourselves, because it is done in C++ standard library. We only have to include the header file and use it. #include Class string

HL2 Advantages: You don’t have to give the length in the declaration. Memory area expands automatically. Assignment works (is real deep copy). Comparison can be done with comparison operator (means alphabetical order ). Input (>>) and output (<<) operators are defined for string. String example Simple example program: #include using namespace std; void main (void) { string str1, str2; cout << "\nEnter a string"; cin >> str1; str2 = str1; //assignment is OK cout << "\nCopy of string 1 is : " << str2; cout << "\nEnter a string"; cin >> str2; if (str1 < str2) //comparison is OK cout << str1 << ”is less than” << str2 ; else cout or equal to” << str1 ; cout << "\nThe capasity of the str2 is " << str2.capacity(); cout << "\nThe size (lenght) of the str2 is " << str2.size(); }

HL3 Basic operations of string Actually string is instantiated from the class template basic_string in the following way: typedef basic_string string; We will learn about class templates later. Constructors string s1; //default string s2(”abcdefg”); //initialising with c-string string s3(10, ’A’); //initialising with n characters Assignment operator s1 = ”abcde”; //assigning a c-string s2 = ’X’; // assigning a character s3 = s1; // assigning another string Input and output operators are defined cout << s1; //display a string cin >> s1; //input is delimited by white space getline(cin, s2); //read a whole line More about assignment (two expressions are same): s1 = s2; s1.assign(s2); Accessing individual characters (indexing and at member function): char chr; chr = s1[ i ]; // rigth vals1[ i ] = ’X’; //left val chr = s1.at( i ); // rigth vals1.at( i ) = ’X’; // -”-

HL4 Concatenation and comparison Concatenation string s1(”Espoo-”); string s2(”Vantaa ”); string s3(”xxxTechnicalxxx”); string s4; s4 = s1 + s2; s1+=s2; s1.append(s2); s4 = s4.append(s3, 3, 9); // Append substring of s3 String comparisons Operators ==, !=,, >= (return value bool). Member function compare (return value <0, 0, or >0 as from strcmp). if (s1.compare(s2) == 0) cout << ”Strings are identical”; Comparing substring with overloaded functions if(!s1.compare(2, 5, s2, 10, 5)) { cout << ”Strings s1 and s2 contain same”; cout << ” substring of 5 characters”; cout << ”starting at character position 2”; cout <<” in s1 and character position 10 in s2; }

HL5 Substrings, size, length and capacity Taking substrings string s1(”Espoo-Vantaa Institute of Technology”); string s2, s3; s2 = s1.substr(0, 5);//Espoo s3 = s1.substr(13, 9);//Institute Swapping strings string s1(”Espoo”); string s2(”Vantaa”); s1.swap(s2); //s1 contains Vantaa and s2 Espoo Member functions length, size, capacity and max_size length and size return the number of characters of the string currently stored in string. capacity returns the number of characters that can be stored in the string without reallocation max_size returns the absolute upper limit for the size of string in the current environment. Example. string s1; cout << s1.size() << s1.length() << s1.capacity(); s1 = ”abcdef”; cout << s1.size() << s1.length() << s1.capacity(); s1.resize(s1.size() + 5); cout << s1.size() << s1.length() << s1.capacity(); s1.reserve(30); cout << s1.size() << s1.length() << s1.capacity();

HL6 Allocation policy As we saw in the previous page, the size (length) of the string can be different from the capacity. The memory allocation policy can be different in different systems but the following example gives an idea of how it could work (this is the case in DevCpp). Example. Size CapacityContents string s; // 00Empty s = “abcd”;// 44|abcd| s.reserve(8);// 48|abcd| s = s + “efg”;// 78|abcdefg| s = s + “hij”;// 1010|abcdefghij| s.resize(14);// 1414|abcdefghij □□□□ | s.reserve(20);// 1420|abcdefghij □□□□ | s.resize(17)// 1720|abcdefghij □□□□□□□ | □ represents a space in the example above

HL7 Find and replace Finding substrings and characters string s1(”xxcxxxabcxxxxxxxxabcxxxxxx”); int pos; pos = s1.find(”abc”); // 6 (find string “abc”) pos = s1.rfind(”abc”); //17 (reverse find) pos = s1.find_first_of(”abc”);//2 (find one char) pos = s1.find_last_of(”abc”);//19 (reverse find) pos = find_first_not_of(”xac”);//7 (find one char) pos = find_last_not_of(”xac”);//18 (reverse find) The return value of find is string::npos if not found. Replacing substrings and characters string s1(”Espoo-Vantaa Institute of Technology”); s1.erase(5);//Espoo string s2(”xxxxxyyyxxxxxxxxxxx”); s2.replace(5, 3, ”abc”);//xxxxxabcxxxxxxxxxxx s2.replace(5,3, ”abcedfYYYghi”, 6,3); //xxxxxYYYxxxxxxxxxxx Inserting strings string s1(”Espoo Institute of Technology”); string s2(”xxxxxVantaayyyyy”); //s1.insert(5, ”-Vantaa”);//Espoo-Vantaa Institute of.. s1.insert(5, ”-”).insert(6, s2, 5, 6); //--”--

HL8 Conversions and iterators Conversions to C-string (member functions copy, data and c_str) copy size_t copy( char *cb, size_t n, size_t pos = 0 ); Function copies from the C++ string to the C character array. You need to add terminating zero yourself. data const char *data() const; c_str const char *c_str() const; String streams In memory I/O. Include files iostream and sstream are needed Classes istringstream and ostringstream Member function str of ostringstream. Connecting buffer or not connecting memory buffer. C++-style or C-style string buffer See example in the following page. Iterators (to be discussed later) class string::const_iterator; string member functions begin and end; iterator comparison operators dereference operator increment operators string::reverse_iterator string::const_reverse_iterator These two functions work in similar way at least in DevCpp

HL9 String streams We have used input streams to read information from the keyboard and output streams to display information. Input streams and output stream make conversions as we see in the following example int a = 127; double b; cout << a; // conversion is done from int to chars cin >> b; // conversion is done from chars to double When we write (<<) information to the stream, it goes to the display. When we read (>>) information from the stream it comes from the keyboard. In the lab exercises 5 we saw that we can connect a stream to the disk file. It is also possible to specify a stream that contains a string. In this case when we write data to the stream it goes to the string and when we read the stream, data comes from the string. This is useful when we need to make conversions. See an example program in the following page.

HL10 String streams example // This program demonstrates how to use string // streams to make conversions from numbers to // strings and vice versa int main() { // Convert a number to string string num_str; int num_int = 127; ostringstream string_stream; string_stream << num_int; num_str =string_stream.str(); // now we have it // as a string // Convert a string to the number string num_str(“127”); int num_int; istringstream string_stream(num_str); string_stream >> num_int; // now we have it // as int }