Definition of Strings Generally speaking, a string is a sequence of characters c string c++ string class Examples: “hello”, “high school”, “H2O”. Typical.

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

Strings.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
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.
Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
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.
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.
1 CS 105 Lecture 8 Strings; Input Failure Mon, Mar 7, 2011, 3:39 pm.
The Standard String Class Is actually a template: –typedef basic_string string This means you can have strings of things other than chars.
1 Lecture 19:String Data Type Introduction to Computer Science Spring 2006.
 2006 Pearson Education, Inc. All rights reserved Class string and String Stream Processing.
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.
CS 31 Discussion, Week 6 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
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.
Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Working with Strings Lecture 2 Hartmut Kaiser
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.
Chapter 10. Characters, Strings and the string class Csc 125 Introduction to C++ Fall 2005.
C++ PROGRAMMING: PROGRAM DESIGN INCLUDING DATA STRUCTURES, FIFTH EDITION Chapter 10: Strings and string type.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
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.
Characters, Strings, And The string Class Chapter 10.
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.
© 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
String Class Mohamed Shehata 1020: Introduction to Programming.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
CS 1430: Programming in C++ 1. Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
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*
1 Strings in C++ The string Class Definition of Strings How to declare strings in C++: the string class Operations on strings –Concatenation, comparison.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
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.
Unit I Objects & Classes in C++:Declaring & using classes,Constructors, Objects as function arguments, Copy Constructors, Static class data, Arrays of.
Strings. Using strings as abstract value A string is a sequence of characters e.g. “Hello, World!” Early version of C++ followed the older C language.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
Strings.
Class string and String Stream Processing: A Deeper Look
Standard Version of Starting Out with C++, 4th Edition
C++ STRINGS string is part of the Standard C++ Library
Strings in C++.
String class and its objects
Class string and String Stream Processing
Representation and Manipulation
Engineering Problem Solving with C++, Etter
Standard Version of Starting Out with C++, 4th Edition
Std Library of C++.
Today’s Objectives 28-Jun-2006 Announcements
Programming Strings.
character manipulation
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

Definition of Strings Generally speaking, a string is a sequence of characters c string c++ string class 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

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 5th.

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

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: std::string x; using namespace std; string x(“high school”); string x= “high school”; string x; x=“high school”;

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”; Output: z=highschool z= highschool was fun

Concatenation of Mixed-Style Strings In s= u + v + w 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

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!

More Examples of Concatenation // The + operator can be used with any combination of // C++ strings, C strings and characters ... strL = strA + strB; strM = "Boo" + strB; strN = strB + "Boo"; strO = '*' + strB; strP = strB + '*';

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.

strH += strA; strJ += "Hello"; strK += 'X'; += Examples strH += strA; strJ += "Hello"; strK += 'X';

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.

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<<“p>x”<<endl; Else cout<<“p<=x”<<endl; Output: x<y x<tree low != x p>x

More Comparison Examples string strA = "hello"; string strB = "a"; if ( strA == "hello" ) cout << "got it" << endl; if ( "hello" == strA ) cout << "got it again" << endl; if ( strB != strA ) cout << "not equal works!" << endl; if ( strA > "Hello" ) cout << "Caps are less" << endl;

The Index Operator [] These allow C++ strings to be used like arrays of characters 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]; string x= “high”; char c=x[0]; // c is ‘h’ c=x[1]; // c is ‘i’ c=x[2]; // c is g

<< and >> This >> function gets a string value from the input stream is, and assigns it to str. istream& operator>>( istream& is, string& str); This << function writes the value of str to the output stream os ostream& operator<<( ostream& os, const string& str); getline inputs a string value. Input stops at end of line by default

Input and Output Examples string strA = "hello boys and girls"; cout << strA << endl; cin >> strA; getline(cin,strA);

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();

Example: using length() in a for loop string strA = "hello"; printCstring(strA.c_str()); for ( int i = 0; i < strA.length(); i++ ) cout << strA.data()[i]; cout << endl;

Obtaining Substrings of Strings A substring of a string x is a subsequence of consecutive characters in x For example, “rod” is a substring of “product” substr returns a substring without modifying the string to which the function was applied. Define the substring as index position up to length The default value for position is 0 The default value of the length is x.length( int pos = 4; int len = 12; string y = x.substr(pos,len); string y = x.substr(pos); //x[pos..end-1]

substr Examples string strA = "123456789"; strB = strA.substr(2,3); // value is "345" strC = strA.substr(2); // value is "3456789"

Inserting a String Inside Another Suppose x is a string object, and let y be another string to be inserted at position pos of the string of x To insert y, do: The argument y can be: a string object, a C-style string variable, or a double-quoted string x.insert(pos,y);

Replacing a Substring by Another Suppose x is a string object, and suppose you want to replace the characters in the range [pos,pos+len) in x by a string y. To do so, write: The argument y can be: a string object, a C-style string variable, or a double-quoted string x.replace(pos,len,y);

strE = "12345"; strE.replace(1,2,3,'B'); // value is "1BBB45" Replace Example strE = "12345"; strE.replace(1,2,3,'B'); // value is "1BBB45"

Deleting (Erasing) a Substring of a string Object Suppose x is a string object, and suppose you want to delete/erase the characters in the range [pos,pos+len) in x. To do so, write: The default value of len is the x.length( ) The default value for pos is 0 To erase the whole string of x, do: x.erase(pos,len); x.erase(pos); // erases x[pos..end-1] x.clear( );

Examples of erase string strD = "123456789"; strD.erase(3,5); // value is "1239" strD.erase(2); // value is "12" strD.erase(); // value is ""

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 exists; otherwise, the method returns the length of x (string::npos). To search starting from a position pos, do int startLoc = x.find(y); int startLoc = x.find(y, pos);

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);

An Example string x=“FROM:ayoussef@gwu.edu”; 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 ayoussef@gwu.edu

What if You Want to Use C-Style Strings You can! C has a library <strings.h> 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[];

C Library <strings.h> for String Operations char *strcpy(char *dst, char *src); Copies the string src to string dest char *strncpy(char *dst, char *src, int n); Copies the first n characters of src to dest char * strcat(*dst, char *src); Concatenate src to the end of dst. char * strcat(*dst, char *src, int n); Concatenate first n chars of src to end of dst.

References www.seas.gwu.edu/~ayoussef/cs103/lecture5.ppt nepsweb.co.uk/pgtcpp/string.htm