String Class Mohamed Shehata 1020: Introduction to Programming.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter 10.
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 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
1 Lecture 19:String Data Type Introduction to Computer Science Spring 2006.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
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.
1 Chapter 10 Characters, Strings, and the string class.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
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
 2006 Pearson Education, Inc. All rights reserved Arrays.
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.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Numeric Types, Expressions, and Output ROBERT REAVES.
Chapter 6 One-Dimensional Arrays ELEC 206 Computer Tools for Electrical Engineering.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
1 C++ Syntax and Semantics, and the Program Development Process.
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.
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
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.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
An Introduction to C++ A First Look. void Functions #include #include void main( ) { cout
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 
Sahar Mosleh California State University San MarcosPage 1 The C++ String Class The contents of this particular lecture prepared by the instructors at the.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
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.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
Arrays, Vectors, and Strings Allocation and referencing.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
Chapter Characters, Strings, and the string class 10.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
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.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
Strings.
CS Computer Science IA: Procedural Programming
C Programming Tutorial – Part I
Review of Strings which include file needs to be used for string manipulation? what using statement needs to be included fro string manipulation? how is.
Announcements 2nd homework is due this week Wednesday (October 18)
Engineering 1020: Introduction to Programming Fall 2018
Introduction to C++ Programming
Summary of what we learned so far
10.1 Character Testing.
Announcements 3rd homework is due this week Wednesday (March 15)
Review of Strings which include file needs to be used for string manipulation? what using statement needs to be included for string manipulation? how is.
Wednesday 09/23/13.
Representation and Manipulation
Introduction to Computer Science
Std Library of C++.
Today’s Objectives 28-Jun-2006 Announcements
character manipulation
An Introduction to STL.
Announcements HW1 is due TODAY.
Presentation transcript:

string Class Mohamed Shehata 1020: Introduction to Programming

Classes Classes are the next higher (above functions) level of modularization in C++ Among other things, classes give us a technique for implementing new data types and operations on them (data abstraction). Many useful classes are already defined in class libraries and in this course the focus is on how to use a class, in particular the string class.

C++ string Classes C++ standard library strings are usable in a manner similar to the built-in types – Remember, a variable's/object's type determines what operations may be performed on it. Note: – #include is required – There are functions for operations such as insert, erase, replace, clear, etc.

String declaration: string myName; // mystr is empty Value assignment at declaration: string myName(”Mohamed”); // myName is initialized to string myName2=”Mohamed”; //the string ”Mohamed” string myName3(myName2); string mystr(5,’n’); // mystr = “nnnnn” myName, myName2, myName3, and mystr are called objects of the string class String Declaration

String Assignment I can assign strings to different values string myName = “John Smith"; //initialization myName = “Mohamed Shehata"; //assignmnet The object myName is now Mohamed Shehata, the original John Smith is not there anymore Assignments from other types are not permitted: string error1 = ’c’;// error - character string error2 = 22;// error - integer

string s1, s2, s3; s1=”1020”; s2=”Introduction to Programming”; Plus “ + ” is used for string concatenation: s3=s1 + ”-” + s2; – at least one operand has to be string variable! So S3 now is “1020-Introduction to Programming” Compound concatenation allowed: s1 += ”course”; Only Characters can be concatenated with strings: s2= s1 + ’o’; s2+=’o’; Concatenation

String can be output as any other type: string s=”hello world”; cout << s << endl; The output on your screen is: hello world Two ways to input strings: – using extraction operator - strips white space and assigns the first “word” to the string: cin >> s; hello world\n – input assigns only hello to s – using getline() function - assigns all characters to string up to newline (not included): getline(cin, s); hello world\n - input assigns hello world to s String I/O

Comparison operators ( >, =, <=, ==, != ) are applicable to strings Strings are compared lexicographically: string s1=”accept”, s2=”access”, s3=”acceptance”; s1 is less than s2 and s1 is less than s3 Order of symbols is determined by the symbol table (ASCII) – letters in the alphabet are in the increasing order – longer word (with the same characters) is greater than shorter word Comparing Strings

Comparison to literal string constants and named constants is also legal: const string myname=”John Doe”; string hername=”Jane Doe”; if ((myname==hername)||(myname==”Jake Doe”)) cout << ”found him\n”;

There are a number of functions defined for strings. Usual syntax: string_name.function_name(arguments) Useful functions return string parameters: – size() - current string size (number of characters currently stored in string – length() - same as size() – empty() - true if string is empty Example: string s=”Hello”; cout << s.length(); // outputs 5 String Functions String Characteristics

Characters in a string Characters in a string are actually stored in an array string s=”C++ Program”; C++Program s s[0] s[s.length()-1]

Similar to arrays a character in a string can be accessed and assigned to using its index (start from 0) cout << str[3]; CAREFUL: Could be an error to access an element beyond the size of the string: string s=”Hello”; // size is 5 cout << s[6]; // error Type of the element of the string is character, assigning integers, strings and other types are not allowed s[3] = ”hi”; // compilation error s[3] = 22; // depends on compiler which //might interpret is as ASCII code Accessing Elements of Strings

find function return position of substring found, if not found return global constant string::npos defined in string header – find(substring) - returns the position of the first character of substring in the string – If not found then it retruns string::npos – npos is a static member constant value with the greatest possible value for an element of type size_t. All functions work with individual characters as well: Ex: string s1="acceptance"; unsigned int pos = s1.find("q"); if(pos != string::npos) cout<< pos; else cout<<"not found"; Searching

Let’s use another format to find the second occurrence string problem = "Great Meal"; int pos = problem.find("a"); //return 3 pos = problem.find("a", pos +1); This will cause the search to start immediately after the pos of the first a (that is at 4) and so will return 8 ( thereby resetting pos to 8).

substr - function that returns a substring of a string: substr(start, numb), where start - index of the first character, numb - number of characters Example: string s=”Hello”; // size is 5 cout << s.substr(3,2); // outputs ”lo” Example: string s=”This is cool”; string sub_s=s.substr(8,4); cout << sub_s; // outputs ”cool” Substrings

insert(start, substring) - inserts substring starting from position start string s=”place”; cout << s.insert(1, ”a”); // s=”palace” Inserting

append(string2) - appends string2 to the end of the string string s=”Hello”; cout << s.append(”, World!”); cout << s; // outputs ”Hello, World!” erase(start, number) - removes number of characters starting from start string s=”Hello”; s.erase(1,2); cout << s; // outputs ”Hlo” clear() - removes all characters s.clear(); // s becomes empty Appending, Erasing

Strings can be passed as parameters: – by value: void myfunc(string s); – by reference: void myfunc(string &s); Passing Strings as Parameters

Strings (unlike arrays) can be returned: – string myfunc(int, int); string lastName (){ string last; // write code here to extract last name return last; } Returning Strings

Examples From Previous Exams

Write a function to permanently erase all white spaces in a string starting at certain position. For example: string problem = " Test 1020"; removeSpaces(problem,0); cout<<problem; Outputs: “Test 1020” void removeSpaces(string &line, int pos){ while( line[pos] == ' ') // 'space' line.erase(pos,1); }

Write a function to parse addresses that separated by a semi colon (;). The function should do the following: – remove all leading white spaces – Return the number of s found in the string – Put the individual s in an array This function will not handle situations of an empty line and will not handle situation of an extra semicolon at the end For example: The function will fill the array s as follows: Here is the prototype of the function: int parse (string line, string s [] )

int parse (string line, string s [] ) { int number=0; int start = 0; unsigned int next; do{ removeSpaces(line,start); next = line.find(";", start); if (next != string::npos) { s[number] = line.substr(start, next-start); start = next + 1; // start past the space number++; } else { s[number] = line.substr(start, line.length()-start); number++; } } while (next != string::npos); return number; }

Note that there are many other special cases not handled This is ok as this code is meant to show you only a concept of using strings

Final F2013 hogwarts

Spring 2013 What is the output of calling bar(3); void bar(int b){ const int n=10; string s="3▼▼nisupif"; // ▼ is empty space for (int i=n*b; i>0; i-=b) cout<<s[i%n]; } 3pi is fun