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++

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

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:
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.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Chapter 9: Arrays and Strings
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.
C++ standard strings. Standard library of C++ language STL STL (The main part of standard library of C++ language) Stream classes Stream classes String.
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 Chapter 10 Characters, Strings, and the string class.
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.
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.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
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.
9-1 Learning Objectives  An Array Type for Strings  C-Strings.
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.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
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.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
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.
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.
CSC 270 – Survey of Programming Languages
String Class Mohamed Shehata 1020: Introduction to Programming.
SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.
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.
Arrays, Vectors, and Strings Allocation and referencing.
Chapter 9 Strings. Learning Objectives An Array Type for Strings – C-Strings Character Manipulation Tools – Character I/O – get, put member functions.
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.
CMPSC 121- Spring 2015 Lecture 6 January 23, 2015.
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.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
Chapter Characters, Strings, and the string class 10.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Character Sequences. strings are in fact sequences of characters, we can represent them also as plain arrays of char elements. For example, the following.
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.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
Strings.
CS Computer Science IA: Procedural Programming
Characters, C-Strings, and More About the string Class
C++ Strings References: :" iomanip, sstream.
Standard Version of Starting Out with C++, 4th Edition
Engineering 1020: Introduction to Programming Fall 2018
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
Introduction to Computer Science
Std Library of C++.
Today’s Objectives 28-Jun-2006 Announcements
character manipulation
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

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++ 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. – Below are some ways C++ strings (variables/objects of type string ) can be used Note: – #include is required – There are functions for operations such as insert, erase, replace, clear, etc.

String declaration: string mystr; // mystr is empty Value assignment at declaration: string mystr(”Hello”); // mystr is initialized to string mystr2=”Hello”; //the string ”Hello” string mystr3(mystr2); string mystr4(5,’n’); // mystr = “nnnnn” Assignments from other types are not permitted: string error1 = ’c’;// error string error2 = 22;// error Can assign a character with assignment operator: mystr=’n’; String Declaration

String can be output as any other type: string s=”hello world”; cout << s << endl; 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 – do not mix one and the other way of input! String I/O

Can use assignment operator as with other types: string s1, s2, s3; s1=”Intro”; s2=”OOP”; Plus “ + ” is used for string concatenation: s3=s1 + ”to” + s2; – at least one operand has to be string variable! Compound concatenation allowed: s1 += ”duction”; Characters can be concatenated with strings: s2= s1 + ’o’; s2+=’o’; No other types can be assigned to strings or concatenated with strings: s2= 42.54; // error s2=”Catch” + 22; // error Assignment and Concatenation

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 – relying on other ASCII properties (e.g. capital letters are less than small letters) is bad style 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”;

Number of standard functions are 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() – max_size() - maximum number of characters in string allowed on this computer – empty() - true if string is empty Example: string s=”Hello”; cout << s.size(); // outputs 5 String Functions String Characteristics

Similar to arrays a character in a string can be accessed and assigned to using its index (start from 0) cout << str[3]; Could be an error to access an element beyond the size of the string: string s=”Hello”; // size is 5 cout << s[6]; 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 Accessing Elements of Strings

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” Substrings

find family of functions 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 – rfind(substring) - same as find, search in reverse – find_first_of(substring) - finds first occurrence of any character of substring in the string – find_last_of(substring) - finds last occurrence of any character of substr in the string All functions work with individual characters as well: cout << s.find(“l”); Searching

insert(start, substring) - inserts substring starting from position start string s=”place”; cout << s.insert(1, ”a”); // s=”palace” Variant insert(start, number, character) – inserts number of character starting from position start string s=”place”; cout << s.insert(4, 2, ’X’);//s= ”placXXe” – note: ‘x’ is a character not a string Inserting

replace (start, number, substring) - replaces number of characters starting from start with substring – the number of characters replaced need not be the same Example string s=”Hello”; s.replace(1,4, ”i, there”); //s is ”Hi, there” Replacing

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); If string is not modified by a function, then use const: void myfunc(const string &s); Passing Strings as Parameters

Strings (unlike arrays) can be returned: – string myfunc(int, int); Note: passing strings by value and returning strings is less efficient than passing them by reference However, efficiency should in most cases be sacrificed for clarity Returning Strings

C++ string Operations Operations

C++ string Operations

C++ String Operations (more)

C-Style string C-strings are the C language version of strings A string may be comprised of 0 or more characters A string of 1000 characters requires much more storage than a string of 2 characters Thus strings are more complicated than ints The C++ standard library provides a string type that hides the details of how the characters are stored The C programming language uses arrays of characters Note: #include is required

Number of Elements There are two ways to keep track of the number of items in an array: –Keep a count of how many items are in the array –Use a marker after the last valid item in the array C-strings use a marker What is a C-string? –C-string is a null-terminated char array The null character is denoted by '\0’ A null occurs after the last character of the string in the array

C- string Example For an initialization using double quotes, "...", the compiler will insert the null Except for str2 having more room, the following are all equivalent char str1[] = “hi!”; //compiler can determine array’s size char str2[20] = “hi!”; //plenty of room char str3[4] = “hi!”; //min size but allows room for null char str4[] = {‘h’,i’,’!’,’\0’};

C- string Example Example of a length function for C-string int strlength(char mystr[]) { int count = 0; while (mystr[count] ! = ‘\0’) ++count; return count; }

C- string Problems C-strings problems stem from the underlying array With C-style strings the programmer must be careful not to access the arrays out of bounds Consider string concatenation, combining two strings to form a single string – Is there room in the destination array for all the characters and the null? The C++ string class manages the storage automatically and does not have these problems

string_0.cpp string.cpp compare.cpp String Use Examples