1 Strings in C++ The string Class Definition of Strings How to declare strings in C++: the string class Operations on strings –Concatenation, comparison.

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms The C Programming Language.
Advertisements

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.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
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.
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.
Pointers in C Rohit Khokher
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: More on C-Strings and the string Class Starting Out with.
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:
Definition of Strings Generally speaking, a string is a sequence of characters c string c++ string class Examples: “hello”, “high school”, “H2O”. Typical.
Lesson 10 Characters, C-Strings, and the string Class CS1 Lesson John Cole1.
Chapter 10.
C-Strings A C-string (also called a character string) is a sequence of contiguous characters in memory terminated by the NUL character '\0'. C-strings.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
CS Nov 2006 C-strings.
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.
Computer Science 1620 Strings. Programs are often called upon to store and manipulate text word processors chat databases webpages etc.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
1 Chapter 10 Characters, Strings, and the string class.
CHAPTER 8 CHARACTER AND STRINGS
In Addition... To the string class from the standard library accessed by #include C++ also has another library of string functions for C strings that can.
CS 1031 Strings in C++ The string Class Definition of Strings How to declare strings in C++: the string class Operations on strings –Concatenation, comparison.
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.
Strings Representation and Manipulation. Objects Objects : Code entities uniting data and behavior – Built from primitive data types.
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.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Chapter 10. Characters, Strings and the string class Csc 125 Introduction to C++ Fall 2005.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
C++ PROGRAMMING: PROGRAM DESIGN INCLUDING DATA STRUCTURES, FIFTH EDITION Chapter 10: Strings and string type.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10: Characters, Strings, and the string class.
Characters, Strings, And The string Class Chapter 10.
ITI 1120 Lab #5 Contributors: S. Boyd, R. Plesa, A. Felty, D. Inkpen, A. Williams, D. Amyot.
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++
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 10: Characters, C- Strings, and More About.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
© Oxford University Press All rights reserved. CHAPTER 6 STRINGS.
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.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
CSC 270 – Survey of Programming Languages
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
Chapter 15 Strings as Character Arrays
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
An Array Type For Strings. Two ways to represent strings – i.e. “Hello” cstring An array with base type char Older way of processing strings Null character.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Strings, Pointers and Tools
Chapter Characters, Strings, and the string class 10.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
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.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 5 : September 4.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
CS Computer Science IA: Procedural Programming
Standard Version of Starting Out with C++, 4th Edition
Strings in C++.
Standard Version of Starting Out with C++, 4th Edition
C++ Programming Lecture 20 Strings
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

1 Strings in C++ The string Class Definition of Strings How to declare strings in C++: the string class Operations on strings –Concatenation, comparison operators, and [ ] Functions of the string class –length, size, empty, –insert, substr, replace, erase, clear, find Useful char functions in the C library

2 Definition of Strings Generally speaking, a string is a sequence of characters Examples: “hello”, “high school”, “H2O”. Typical desirable operations on strings are: –Concatenation: “high”+“school”=“highschool” –Comparisons: “high”<“school” // alphabetical –Finding/retrieving/modifying/deleting/inserting substrings in a given string

3 Strings in C In C, a string can be a specially terminated char array or char pointer –a char array, such as char str[ ]=“high”; –a char pointer, such as char *p = “high”; If a char array, the last element of the array must be equal to ‘\0’, signaling the end For example, the above str[] is really of length 5: str[0]=‘h’ str[1]=‘i’ str[2]=‘g’ str[3]=‘h’ str[4]=‘\0’ The same array could’ve been declared as: –char str[5] = {‘h’,’i’, ‘g’,’h’,’\0’}; If you write char str[4] = {‘h’,’i’, ‘g’,’h’};, then str is an array of chars but not a string. In char *p=“high”; the system allocates memory of 5 characters long, stores “high” in the first 4, and ‘\0’ in the 5 th.

4 The string Class in C++ C++ has a library Include it in your programs when you wish to use strings: #include In this library, a class string is defined and implemented It is very convenient and makes string processing easier than in C

5 Declaration of strings The following instructions are all equivalent. They declare x to be an object of type string, and assign the string “high school” to it: –string x(“high school”); –string x= “high school”; –string x; x=“high school”;

6 Operations on strings (Concatenation) Let x and y be two strings To concatenate x and y, write: x+y string x= “high”; string y= “school”; string z; z=x+y; cout<<“z=“<<z<<endl; z =z+“ was fun”; cout<<“z=“<<z<<endl; Output: z=highschool z= highschool was fun

7 Concatenation of Mixed-Style Strings In where s is of type string, –u can be  A string object, or  a C-style string (a char array or a char pointer),  a C-style char  or a double-quoted string,  or a single-quoted character. –Same with v and w. –At least u or v or w must be a string object s=u+v+w;

8 Example of Mixed-Style Concat string x= “high”; char y[]= “school”; char z[]= {‘w’,’a’,’s’,’\0’}; char *p = “good”; string s= x+y+’ ‘+z+” very”+” “+p+’!’; cout<<“s=“<<s<<endl; cout<<“s=“+s<<endl; Output: s=highschool was very good!

9 The concat-assign Operator += Assume x is a string object. The statement x += y; is equivalent to x=x+y; where y can be a string object, a C-style string variable, a char variable, a double- quoted string, or a single-quoted char.

10 Comparison Operators for string Objects We can compare two strings x and y using the following operators: ==, !=,, >= The comparison is alphabetical The outcome of each comparison is: true or false The comparison works as long as at least x or y is a string object. The other string can be a string object, a C-style string variable, or a double- quoted string.

11 Example of String Comparisons string x= “high”; char y[]= “school”; char *p = “good”; If (x<y) cout<<“x<y”<<endl; If (x<“tree”) cout<<“x<tree”<,endl; If (“low” != x) cout<<“low != x”<<endl; if( (p>x) cout x”<<endl; Else cout<<“p<=x”<<endl; Output: x<y x<tree low != x p>x

12 The Index Operator [] If x is a string object, and you wish to obtain the value of the k-th character in the string, you write: x[k]; This feature makes string objects appear like arrays of chars. string x= “high”; char c=x[0]; // c is ‘h’ c=x[1]; // c is ‘i’ c=x[2]; // c is g

13 Getting a string Object Length & Checking for Emptiness To obtain the length of a string object x, call the method length() or size(): To check of x is empty (that is, has no characters in it): int len=x.length( ); --or-- int len=x.size( ); bool x.empty();

14 Obtaining Substrings of Strings Logically, a substring of a string x is a subsequence of consecutive characters in x For example, “rod” is a substring of “product” If x is a string object, and we want the substring that begins at position pos and has len characters (where pos and len are of type int), write: The default value of len is x.length( ) The default value for pos is 0 string y = x.substr(pos,len); string y = x.substr(pos);//x[pos..end-1]

15 Searching for (and Finding) Patterns in Strings Suppose x is a string object, and suppose you want to search for a string y in x. To do so, write: This method returns the starting index of the leftmost occurrence of y in x, if any occurrence exits; otherwise, the method returns the length of x. To search starting from a position pos, do int startLoc = x.find(y); int startLoc = x.find(y, pos);

16 Searching for Patterns (Contd.) To search for the rightmost occurrence of y in x, do In all the versions of find and rfind, the argument y can be a string object, a C-style string variable, double-quoted string, a char variable, or a single-quoted char. startLoc = x.rfind(y); // or startLoc = x.rfind(y, pos);

17 An Example string int colonPos=x.find(‘:’); string prefix=x.substr(0,colonPos); //=FROM string suffix = x. substr(colonPos+1); cout<<“-This message is from ”<<suffix<<endl; Output: -This message is from

18 Another Example #include // this code segment reads lines from an input file and // appends them to a string object called body. It does // so until it sees a line equal to ########## ifstream in(“inputFileName.txt”); string body; char line[1000]; while(in.getline(line,1000)){ //puts in line the next line w/o \n string lineString (line); if (lineString != "##########") body += lineString +'\n';// appends line to body else break;// exits the while loop }

19 Trimming Leading & Trailing Spaces // this function removes leading and trailing spaces from x void trim (string& x){ int k = 0; // k will procced to the first non-blank char while(k<x.size() &&(x[k]==' ' || x[k]=='\t' || x[k]=='\n')) k++; x. erase(0,k); int s=x.size(); // s will move backward to the rightmost non-blank char while(s>0 &&(x[s-1]==' ' || x[s-1]=='\t' || x[s-1]=='\n')) s--; x.erase(s); }

20 What if You Want to Use C-Style Strings You can! C has a library which provides several string processing functions Some of the more commonly used functions in that library are presented in the next two slides In those functions, most of the arguments are of type char *str. That can be replaced by char str[];

21 Correspondence between the C library and the C++ string Class C Library FunctionsC++ string operators/methods strcpy= (the assignment operator) strcat+= (assign+concat operator) strcmp= =, !=,, = strchr, strstr strrchr.find( ) method.rfind( ) method strlen.size( ) or.length( ) methods

Assignment 22 Write a C++ program to change the following story into something interesting: “I woke up this morning and took a shower. The water was warm. After my shower, I brushed my teeth. I then ate my breakfast and got dressed. The drive to school was uneventful. Nothing exciting happened on the way. School was boring, except for Programming class. Then I went home and did my homework. It was an average day.” Enter the story in vi – read the story into your program, manipulate the strings and write the new story out to a file.