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.

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

 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
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.
Java Programming Strings Chapter 7.
Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises.
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 CS 105 Lecture 8 Strings; Input Failure Mon, Mar 7, 2011, 3:39 pm.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
1 Lecture 19:String Data Type Introduction to Computer Science Spring 2006.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
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';
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
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.
Working with Strings Lecture 2 Hartmut Kaiser
DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream.
February 14, 2005 Characters, Strings and the String Class.
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
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.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
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++
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
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.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
Chapter 9 Strings. Learning Objectives An Array Type for Strings – C-Strings Character Manipulation Tools – Character I/O – get, put member functions.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
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.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Expressions Version Topics Arithmetic expressions Conversions Operator precedence String class 2.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
Strings.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 9 Strings Copyright © 2016 Pearson, Inc. All rights reserved.
Computing Fundamentals
Basic Elements of C++.
Introduction to C++ October 2, 2017.
Primitive Types Vs. Reference Types, Strings, Enumerations
Standard Version of Starting Out with C++, 4th Edition
Basic Elements of C++ Chapter 2.
Engineering 1020: Introduction to Programming Fall 2018
Introduction to C++ Programming
10.1 Character Testing.
String class and its objects
Variables T.Najah Al_Subaie Kingdom of Saudi Arabia
Wednesday 09/23/13.
Introduction to C++ Programming
Representation and Manipulation
Engineering Problem Solving with C++ An Object Based Approach
Introduction to Computer Science
Using string type variables
Std Library of C++.
COMS 261 Computer Science I
character manipulation
getline() function with companion ignore()
Presentation transcript:

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 of the C++ built-in classes. u C++ strings allow you to directly initialize, assign, compare, and reassign with the intuitive operators, as well as printing and reading (e.g., from the user). nalhareqi©2012

Declaring string Objects u Use the class name string and then list object names. u Example: string str; // declaring one object called str string str1, str2, str3; // str1, str2, and str3 // would be string objects nalhareqi©2012

Initializing string Objects u The string objects can be an initialize with the = operator. –C++ automatically reserves sufficient memory string str1 = "This is an example."; string str2 = str1; /* create a string object called str2 and initialize it with a copy of str1*/ nalhareqi©2012

Reading a string input string str1 u To read a single word: cin >> str1; –Reads characters until whitespace typed –Whitespace includes space and "Enter" key u To read a single line of input: getline (cin, str1); nalhareqi©2012

Example u string name; cout > name; cout << “Welcome " << name <<“\n Have a nice day \n”; Enter your name: Majed Ali Welcome Majed Have a nice day nalhareqi©2012

Example u string name; cout << "Enter your name: " << endl; getline (cin, name); cout << “Welcome " << name <<“\n Have a nice day \n”; Enter your name: Majed Ali Welcome Majed Ali Have a nice day nalhareqi©2012

strings concatenation with the + operator u C++ strings also provide many string manipulation facilities. The simplest string manipulation that we commonly use is concatenation, or addition of strings. In C++, we can use the + operator to concatenate (or “add”) two strings, as shown below : string result; string s1 = "hello "; string s2 = "world"; result = s1 + s2; // result now contains "hello world" Notice that both s1 and s2 remain unchanged! nalhareqi©2012

strings concatenation with the + operator u You can also use two or more + operators to concatenate several (more than 2) strings. string firstname, lastname, fullname; cout << "First name: "; getline (cin, firstname); // if firstname = “Bader” cout << "Last name: "; getline (cin, lastname); // if lastname = “Yasser” fullname = lastname + ", " + firstname; // fullname = “Yasser, Bader” cout << "Fullname: " << fullname << endl; nalhareqi©2012

strings concatenation with the + operator u We can also use the + to concatenate multiple strings to be printed as one string. fullname = lastname + ", " + firstname; cout << "Fullname: " << fullname << endl; cout << "Fullname: "+lastname+ ", " + firstname <<endl; cout <<"Fullname:"+lastname+ ", " + firstname + ”\n”; nalhareqi©2012

strings concatenation with the += operator u The += operator can also be used. In that case, one string is appended to another one: u After execution of the above statements, result contains the string "hello world". string result; string s1 = "hello"; // without the extra space at the end string s2 = "world"; result = s1; result += ' '; // append a space at the end result += s2; Note += Concatenates and stores nalhareqi©2012

Comparing string Objects u Equality and relational operators perform comparisons using the numerical values of the characters in each string. OperatorAction ==True if strings identical !=True if strings not identical >True if first string greater than second <True if first string is less than second >=True if first string greater or equal than second <=True if first string less or equal than second nalhareqi©2012

Example u string s1 = "abc def abc"; string s2 = "abcde uvwxyz";  s1< s2 ?? u Uses ASCII code to determine which string is smaller. u Here the condition is true because a space comes before letter d nalhareqi©2012

Examples #include using namespace std; int main () { string s1,s2; s1="abc" ; s2="abc"; cout<< "(s1==s2) :"<<(s1==s2)<<endl; s1="abc " ; s2="abcd"; cout<< "(s1<s2) :" <<(s1<s2)<<endl; s1="{abc}"; s2="abc"; cout<< "(s1<s2) :"<<(s1<s2)<<endl; return 0; } nalhareqi©2012

ASCII code nalhareqi©2012 char let='a'; cout<<"let :"<<let <<endl; cout<<"ASCII code for let : "<<(int)let<<endl;

Access a character of string u The subscript operator, [ int ], can be used with strings to access and modify individual characters. u The strings have a first subscript of 0. nalhareqi©2012 string x = “hello”; char c = x[0]; // c is ‘h’ c = x[1]; // c is ‘e’ c = x[2]; // c is ‘l’ hello X

Operators on string Objects Type OperatorAction Assignment=Stores string +=Concatenates and stores Comparison==True if strings identical !=True if strings not identical >True if first string greater than second <True if first string is less than second >=True if first string greater or equal than second <=True if first string less or equal than second Input/Output>>For input and string objects <<For output and string objects Character[ ]To access individual characters access Concatenation +Connects two strings nalhareqi©2012

Some string Functions u More actions needed than operators can be provided by using string class’s functions - Examples: length, find, substr, empty, insert. u Calling member function involves using object name with dot operator and function name nalhareqi©2012

length Function u To obtain the length of a string object, call the method length() ob. length() - it return the length of the ob. int n; string str = "exam"; n = str.length(); //n=4 nalhareqi©2012

find Function u Searches for a string within a string u Basic form of call to find ob1.find (ob2); –finds first occurrence of string ob2 within ob1 u Returns position int n ; string s1,s2 s1 = "This is an example."; s2 = "exam"; n = s1.find(s2); \\ n =11 n = s1.find(‘ ‘); \\ n = nalhareqi©2012

find Function u Another version has two arguments u Basic form: ob1.find (ob2, index); –index represents integer value for beginning of search u String not found returns -1 nalhareqi©2012 string s ="Hi! How are you? "; int n= s.find(‘H’, 1); //n =4

substr Function u We can extract one portion of a string with the method substr. u This does not remove the portion from the original string; instead, it creates a new string that contains the specified portion of the original string. nalhareqi©2012

substr Function u The required substring is specified by the starting position and the number of characters, taking into account that the position of the first character in the string is 0. ob.substr( int, int) positionNumber of character string text = "hello world, this is a test"; string fragment = text.substr(6, 5); // start at 6, take 5 characters // fragment = “world” nalhareqi©2012

substr Function u When the second argument is not specified, substr returns the remainder of the string on which it’s called. ob.substr( int) string text = "hello world"; string subs = text.substr(3); // subs = “lo world” nalhareqi©2012

empty Function u the empty function determines whether a string object is empty or not. ob.empty(); u The function empty returns true if the string is empty; otherwise, it returns false. Str = “ Hi “; bool flag = Str.empty(); // flag = False cout<< flag <<end; // output: 0 nalhareqi©2012

insert Function u Adds characters (string) to a string object ob1.insert(index, ob2); –index is beginning position –ob2 represents what is to be inserted u Returns reference to the invoking function s1 = "This is an example."; s1.insert (8,"just "); \\s1 = "This is just an example.“ nalhareqi©2012

Example nalhareqi©201228

Conditional operator  The ? operator is called a conditional operator and has the following general form Exp1 ? Exp2 : Exp3; u where Exp1, Exp2, and Exp3 are expressions. u Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. nalhareqi©201229

Conditional operator u The ? is called a ternary operator because it requires three operands. int var, y; var = (y < 10) ? 30 : 40; // if y = 5  var =30 //if y = 10  var =40 nalhareqi©201230

Example nalhareqi©201231

Example nalhareqi©201232

Example nalhareqi©201233

Example nalhareqi©201234

Example nalhareqi©201235