SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.

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.
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.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: More on C-Strings and the string Class Starting Out with.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 19 - Class string and Stream Processing Outline 19.1Introduction 19.2 string Assignment and.
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.
Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Standard Template Library Ming.
The Standard String Class Is actually a template: –typedef basic_string string This means you can have strings of things other than chars.
計算機概論實習 How to Use string Template class basic_string String manipulation (copying, searching, etc.) typedef basic_string string; Also typedef.
 2006 Pearson Education, Inc. All rights reserved Class string and String Stream Processing.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
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.
C++ standard strings. Standard library of C++ language STL STL (The main part of standard library of C++ language) Stream classes Stream classes String.
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.
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.
Working with Strings Lecture 2 Hartmut Kaiser
C++ String Class. Outline  String Initialization  Basic Operations  Comparisons  Substrings  Swapping Strings  String Size  Finding Strings and.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: More on C-Strings and the string Class Starting Out with.
Chapter 10. Characters, Strings and the string class Csc 125 Introduction to C++ Fall 2005.
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 © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10: Characters, Strings, and the string class.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
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++
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 15 - Class string and String Stream Processing Outline 15.1 Introduction 15.2 string Assignment.
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.
Arrays, Vectors, and Strings Allocation and referencing.
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.
LECTURE 6 cs201 C++ Strings.
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*
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Chapter Characters, Strings, and the string class 10.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
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.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Strings.
2008YeungNam Univ. SE Lab. 1  I n n amespace std : t ypedef basic_string string ; Type wchar_t for 16bit UNICODE. A. String near-containers  I.
C-Strings We have already seen that a C-string is a null-terminated array of characters.
Class string and String Stream Processing: A Deeper Look
Characters, C-Strings, and More About the string Class
Chapter 12: More on C-Strings and the string Class
Standard Version of Starting Out with C++, 4th Edition
Engineering 1020: Introduction to Programming Fall 2018
C++ STRINGS string is part of the Standard C++ Library
10.1 Character Testing.
String class and its objects
Class string and String Stream Processing
Engineering Problem Solving with C++, Etter
Standard Version of Starting Out with C++, 4th Edition
Today’s Objectives 28-Jun-2006 Announcements
Chapter 15 - Class string and String Stream Processing
character manipulation
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture 11. Strings

Software Design II – C++ Strings 2December 25, 2015 Design and programming are human activities; forget that and all is lost. --Bjarne Stroustrup, 1991

Software Design II – C++ Strings 3December 25, 2015 C-string C++ - string Array of chars that is null terminated (‘\0’). Object whose string type is defined in the header file has a large repertoire of functions (e.g. length, replace, etc.) char cs[ ] = “Napoleon”; // C-string string s = “Napoleon”; // C++ - string cout << s << “ has “ << s.length() << “ characters.\n”; s.replace(5, 2,”ia”); //changes s to “Napolian String Objects

Software Design II – C++ Strings 4December 25, 2015 Formatted Input: Stream extraction operator cin >> stringObject; >> the extraction operator >> formats the data that it receives through its input stream; it skips over whitespace Unformatted Input: getline function for a string getline( cin, s) does not skip over whitespace delimited by newline reads an entire line of characters into s string s = “ABCDEFG”; getline(cin, s); //reads entire line of characters into s char c = s[2]; //assigns ‘C’ to c S[4] = ‘*’; //changes s to “ABCD*FG” String Objects cin 输入: cout s 输出:

Software Design II – C++ Strings 5December 25, 2015 Not necessarily null terminated string is not a pointer, but a class Many member functions take start position and length If length argument too large, max chosen String Objects

Software Design II – C++ Strings 6December 25, 2015 #include using namespace std; //string initialization string s; //s contains 0 characters string s1( "Hello" ); //s1 contains 5 characters string s2 = “Hello”; //s2 contains 5 characters //implicitly calls the constructor string s3( 8, 'x' ); //s3 contains 8 'x' characters string s4 = s3; //s4 contains 8 'x' characters string s5(s2, 3, 2); //s5 copies a substring of s2; it contains ”lo” string type in the header file. String Objects

Software Design II – C++ Strings 7December 25, 2015 string s = “ABCDEFG”; const char* cs = s.c_str(); Converts s into the C-string cs. C++ strings can be converted to C-strings: The c_str() function has a return type const char* String Objects

Software Design II – C++ Strings 8December 25, 2015 cout << s.length() << endl; Prints 4 for the string s == “Leon” The C++ string class also defines a length() function for extracting how many characters are stored in a string. You can also use the subscript operator [ ] to access individual characters: e.g. s[0] = ‘N’ ; //where index: 0 to length-1 String Objects

Software Design II – C++ Strings 9December 25, 2015 If(s2 < s5) cout << “s2 lexicographically precedes s5 \n”; while(s4==s3) //… 'B' is lexicographically greater than 'A' C++ strings can be compared using relational operators just like fundamental types: Sample order: ‘A’,”Apple”, “Banana”, “Zest”, ‘a’, “apricot”, “leon” String Objects

Software Design II – C++ Strings 10December 25, 2015 string s = “ABCD*FG”; string s2 = “Robot”; string s5 = “Soccer”; string s6 = s + “HIJK”; //changes s6 to “ABCD*FGHIJK” s2 += s5; //changes s2 to “RobotSoccer” You can also concatenate C++ strings using the + and += operators: String Objects

Software Design II – C++ Strings 11December 25, 2015 s6 = “ABCD*FGHIJK”; s4 = s6.substr(5, 3); //changes s4 to “FGH” Substring function: substr() s4 gets a substring of s6, starting at index 5 and taking 3 characters String Objects

Software Design II – C++ Strings 12December 25, 2015 s6 = “ABCD*FGHIJK”; s6.erase(4, 2); //changes s6 to “ABCDGHIJK”; s6.replace(5, 2, “xyz”); //changes s6 to “ABCDGxyzJK”; erase() and replace() functions: replace 2 characters from s6, starting at index 5, with “xyz” String Objects

Software Design II – C++ Strings 13December 25, 2015 string s7 = “Mississippi River basin”; cout << s7.find(“si”) << endl; //prints 3 cout << s7.find(“so”) << endl; //prints the length of the string find() function returns the index of the first occurrence of a given substring: If the find() function fails, it returns the length of the string it was searching. i.e. find(“so”) returns 4,294,967,295 String Objects

Software Design II – C++ Strings 14December 25, 2015 Assignment Assignment Assignment s2 = s1; Makes a separate copy s2.assign(s1); Same as s2 = s1; myString.assign(s, start, N); Copies N characters from s, beginning at index start Individual character assignment s2[0] = s3[2];

Software Design II – C++ Strings 15December 25, 2015 Range-checking s3.at( index ); index Returns character at index out_of_range Can throw an out_of_range exception [] has no range checking #include... s string s = "leon"; try{ s char letter = s.at( 50 ) ; cout <<"letter is = " << letter << endl; } catch(exception& e){ what() cout << "out_of_range exception: " << e.what() << endl; }

Software Design II – C++ Strings 16December 25, 2015 Concatenation Concatenation Concatenation s3.append( "pet" ); s3 += "pet"; Both add "pet" to end of s3 s3.append( s1, start, N ); Ns1start Appends N characters from s1, beginning at index start

Software Design II – C++ Strings 17December 25, 2015 Comparing strings Overloaded operators ==, !=,, = returns bool s1.compare(s2) returns positive if s1 is lexicographically greater compares letter by letter 'B' lexicographically greater than 'A‘ ‘a’ lexicographically greater than ‘A‘ ‘a’ lexicographically greater than ‘Z‘ returns negative if less; zero if equal Sample order: ‘A’,”Apple”, “Banana”, “Zest”, ‘a’, “apricot”, “leon” s1.compare(start, length, s2, start, length) Compare portions of s1 and s2 s1.compare(start, length, s2) Compare portion of s1 with all of s2

Software Design II – C++ Strings 18December 25, 2015 Substrings Function substr gets a substring s1.substr( start, N ); gets N characters, beginning with index start returns substring

Software Design II – C++ Strings 19December 25, 2015 Swapping strings s1.swap(s2); Switch contents of two strings

Software Design II – C++ Strings 20December 25, 2015 string Characteristics Member functions s1.size() and s1.length() Number of characters in a string s1.capacity() Number of elements that can be stored without reallocation 编译器为 string 预分配内存的大小 s1.max_size() Maximum possible string size s1.empty() Returns true if empty s1.resize(newlength) Resizes string to newlength

Software Design II – C++ Strings 21December 25, 2015 Finding Strings and Characters in a string Find functions Find functions If found, index returned If not found, string::npos returned Public static constant in class string s1.find( s2 ) s1.rfind( s2 ) Searches right-to-left s1.find_first_of( s2 ) Returns first occurrence of any character in s2 Example: s1.find_first_of( "abcd" ) Returns index of first 'a', 'b', 'c' or 'd'

Software Design II – C++ Strings 22December 25, 2015 Finding Strings and Characters in a string Find functions Find functions s1.find_last_of( s2 ) Finds last occurrence of any character in s2 s1.find_first_not_of( s2 ) Finds first character NOT in s2 s1.find_last_not_of( s2 ) Finds last character NOT in s2

Software Design II – C++ Strings 23December 25, 2015 Replacing Characters in a string s1.erase( start ) Erase from index start to end of string, including start Replace s1.replace( begin, N, s2) begin : index in s1 to start replacing N : number of characters to replace s2 : replacement string s1.replace( begin, N, s2, index, num ) index : element in s2 where replacement comes from num : number of elements to use when replacing Replace can overwrite characters

Software Design II – C++ Strings 24December 25, 2015 Example s1.replace( begin, N, s2, index, num ) begin : index in s1 to start replacing N : number of characters to replace s2 : replacement string index : element in s2 where replacement comes from num : number of elements to use when replacing. string str = "this is an example string."; string str3="sample phrase"; str.replace(19,6, str3, 7, 6);// "" str.replace(19,6, str3, 7, 6); // "this is an example phrase."

Software Design II – C++ Strings 25December 25, 2015 Inserting Characters into a string s1.insert( index, s2 ) Inserts s2 before position index s1.insert( index, s2, index2, N ); Inserts substring of s2 before position index Substring is N characters, starting at index2

Software Design II – C++ Strings 26December 25, 2015 Conversion to C-Style char* Conversion functions String s are not necessarily null-terminated s1.copy( ptr, N, index ) Copies N characters into the array ptr Starts at location index Need to null terminate char str[8]; string s2 = "cathode"; s2.copy(str, 5, 2); //copy 5 characters into str //starting at index 2 //strcat(str,"\0"); //does not work str[5] = '\0'; //this is required cout << "str = " << str << endl; cout << "s2 = " << s2 << endl; Output: str = thode s2 = cathode

Software Design II – C++ Strings 27December 25, 2015 Conversion to C-Style char * Strings Conversion functions s1.c_str() Returns const char * Null terminated e.g. Useful for filenames: ifstream in( s1.c_str() ); s1.data() Returns const char * NOT null-terminated

Software Design II – C++ Strings 28December 25, 2015 Warning! No conversion No conversion from int or char The following definitions could return errors, or warnings only, but then would cause the program to crash afterwards string error1 = 'c'; string error2( 'u' ); string error3 = 22; string error4( 8 ); However, it can be assigned one char after its declaration: s = 'n';

Software Design II – C++ Strings 29December 25, 2015 String Stream Processing I/O of strings to and from memory Called in-memory I/O or string stream processing Classes istringstream // input from string ostringstream // output to a string stringstream( string ) // most useful Requires and headers Use string formatting to save data to memory allows a string to be used as an internal file useful for buffering input and output

Software Design II – C++ Strings 30December 25, 2015 Serves as a conduit to an anonymous string which can be read () with the built-in oss.str() function that is bound to the oss object ostringstream oss; int n = 44; float x = 3.14; oss << "Hello!\t" << n << '\t' << x; string s = oss.str(); cout << endl << s << endl; Output String Stream

Software Design II – C++ Strings 31December 25, 2015 iss All extractions from iss will come from the contents of buffer, as if it were an external file. const string buffer = oss.str(); istringstream iss(buffer); string word; int m; float y; iss >> word >> m >> y; s = iss.str(); cout << endl << s << endl; cout << "word = " << word << endl; cout << "m = " << m << endl; cout << "y = " << y << endl; iss is defined and bound to buffer Contents of buffer can be accessed as elements of a string, or by formatted input through the iss object. Input String Stream

Software Design II – C++ Strings 32December 25, 2015 #include using namespace std; int main(){ string s1("mydata.txt"); ifstream in( s1.c_str() ); char buffer[1024]; while( in.getline( buffer, 1024 ) ){ string stemp( buffer ); cout << "Line is:" << stemp << endl; if( stemp[0] != '#' ){ stringstream stris( stemp ); double d1, d2; stris >> d1 >> d2; cout << d1 << "," << d2 << endl; } cout << endl; } in.close(); return 0; } Using string example Input file: # Example Output: Line is: ,2 Line is: ,2.4 Line is: ,2.8 Line is:# Line is: ,8.99

Software Design II – C++ Strings 33December 25, 2015 #include using namespace std; int main(){ string s1("mydata.txt"); ifstream in( s1.c_str() ); char buffer[1024]; while( in.getline( buffer, 1024 ) ){ string stemp( buffer ); cout << "Line is:" << stemp << endl; if( stemp[0] != '#' ){ stringstream stris( stemp ); double d1, d2; stris >> d1 >> d2; cout << d1 << "," << d2 << endl; } cout << endl; } in.close(); return 0; } int main(){ string s1("mydata.txt"); ifstream in( s1.c_str() ); string buffer; while(getline( in, buffer ) ){ cout << "Line is:" << buffer << endl; if( buffer[0] != '#' ){ istringstream stris( buffer ); double d1, d2; stris >> d1 >> d2; cout << "data: " << d1 << "," << d2 << endl; } cout << endl; } in.close(); return 0; } Alternatively: (no C-style char*)

Software Design II – C++ Strings 34December 25, 2015 Summary C++ strings are safer and easier to use than C string. Next Templates

Software Design II – C++ Strings 35December 25, 2015 MethodUse append(char *pt); append(char *pt, size_t count); append(string &str, size_t offset,size_t count); append(string &str); append(size_t count, char ch); append(InputIterator Start, InputIterator End); Appends characters to a string from C-style strings, char's or other string objects. at(size_t offset); Returns a reference to the character at the specified position. Differs from the subscript operator, [], in that bounds are checked. begin();Returns an iterator to the start of the string. *c_str();Returns a pointer to C-style string version of the contents of the string. clear();Erases the entire string. copy(char *cstring, size_t count, size_t offset); Copies "count" characters into a C-style string starting at offset. empty();Test whether a string is empty. end();Returns an iterator to one past the end of the string. erase(iterator first, iterator last); erase(iterator it); erase(size_t pos, size_t count); Erases characters from the specified positions.

Software Design II – C++ Strings 36December 25, 2015 MethodUse find(char ch,size_t offset = 0); find(char *pt,size_t offset = 0); find(string &str,size_t offset = 0); Returns the index of the first character of the substring when found. Otherwise, the special value "npos" is returned. find_first_not_of(); Same sets of arguments as find. Finds the index of the first character that is not in the search string. find_first_of(); Same sets of arguments as find. Finds the index of the first character that is in the search string. find_last_not_of(); Same sets of arguments as find. Finds the index of the last character that is not in the search string. find_last_of(); Same sets of arguments as find. Finds the index of the last character that is in the search string. insert(size_t pos, char *ptr); insert(size_t pos, string &str); insert(size_t pos, size_t count, char ch); insert(iterator it, InputIterator start, InputIterator end); Inserts characters at the specified position. push_back(char ch);Inserts a character at the end of the string. replace(size_t pos, size_t count, char *pt); replace(size_t pos, size_t count, string &str); replace(iterator first, iterator last, char *pt); replace(iterator first, iterator last, string &str); Replaces elements in a string with the specified characters. The range can be specified by a start position and a number of elements to replace, or by using iterators. size();Returns the number of elements in a string. swap(string &str);Swaps two strings.

Software Design II – C++ Strings 37December 25, 2015 Thank you!