《软件设计课件:Lecture 11 Strings》由会员分享,可在线阅读,更多相关《软件设计课件:Lecture 11 Strings(37页珍藏版)》请在金锄头文库上搜索。
1、Lecture 11.StringsSoftware Design II C+ Strings2 02 August 2024Design and programming are human activities;forget that and all is lost.-Bjarne Stroustrup, 1991Software Design II C+ Strings4 02 August 2024Formatted Input: Streamextractionoperatorcin stringObject;theextractionoperatorformatsthedatatha
2、titreceivesthroughitsinputstream;itskipsoverwhitespaceUnformatted Input: getlinefunctionforastringgetline( cin, s)doesnotskipoverwhitespacedelimitedbynewlinereadsanentirelineofcharactersintosstrings=“ABCDEFG”;getline(cin,s);/readsentirelineofcharactersintoschar c = s2; /assigns C to c S4 = *; /chang
3、es s to “ABCD*FG”String Objectscin输入:couts输出:Software Design II C+ Strings5 02 August 2024Notnecessarilynullterminatedstringisnotapointer,butaclassManymemberfunctionstakestartpositionandlengthIflengthargumenttoolarge,maxchosenString ObjectsSoftware Design II C+ Strings6 02 August 2024#includeusingna
4、mespacestd;/stringinitializationstrings;/scontains0charactersstrings1(Hello);/s1contains5charactersstrings2=“Hello”;/s2contains5characters/implicitlycallstheconstructorstrings3(8,x);/s3contains8xcharactersstrings4=s3;/s4contains8xcharactersstrings5(s2,3,2);/s5copiesasubstringofs2;itcontains”lo”strin
5、gtypeinthe headerfile.String ObjectsSoftware Design II C+ Strings7 02 August 2024strings=“ABCDEFG”;constchar*cs=s.c_str();Converts s into the C-string cs.C+ strings can be converted to C-strings:Thec_str() functionhasareturntypeconst char*String ObjectsSoftware Design II C+ Strings8 02 August 2024co
6、ut 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.Youcanalsousethesubscript operator toaccessindividualcharacters:e.g.s0 = N ; /where index: 0tolength-1String ObjectsSoftware Design II C
7、+ Strings9 02 August 2024If(s2s5)cout“s2lexicographicallyprecedess5n”;while(s4=s3)/B is lexicographically greater than AC+ strings can be compared using relational operators just like fundamental types:Sample order: A,”Apple”, “Banana”, “Zest”, a, “apricot”, “leon”String ObjectsSoftware Design II C+
8、 Strings10 02 August 2024strings=“ABCD*FG”;strings2=“Robot”;strings5=“Soccer”;strings6=s+“HIJK”;/changess6to“ABCD*FGHIJK”s2+=s5;/changess2to“RobotSoccer”You can also concatenate C+ strings using the + and += operators:String ObjectsSoftware Design II C+ Strings11 02 August 2024s6=“ABCD*FGHIJK”;s4=s6
9、.substr(5,3);/changess4to“FGH”Substring function: substr()s4 gets a substring of s6, starting at index 5 and taking 3 charactersString ObjectsSoftware Design II C+ Strings12 02 August 2024s6=“ABCD*FGHIJK”;s6.erase(4,2);/changess6to“ABCDGHIJK”;s6.replace(5,2,“xyz”);/changess6to“ABCDGxyzJK”;erase() an
10、d replace() functions:replace 2 characters from s6, starting at index 5, with “xyz”String ObjectsSoftware Design II C+ Strings13 02 August 2024strings7=“MississippiRiverbasin”;couts7.find(“si”)endl;/prints3couts7.find(“so”)endl;/printsthelengthofthestringfind() function returns the index of the firs
11、t occurrence of a given substring:If the find() function fails, it returns the length of the string it was searching.i.e.find(“so”)returns4,294,967,295String ObjectsSoftware Design II C+ Strings14 02 August 2024Assignmentl lAssignmentAssignments2 = s1;Makes a separate copys2.assign(s1);Sameass2 = s1
12、;myString.assign(s, start, N);CopiesNcharactersfroms,beginningatindexstartIndividualcharacterassignments20 = s32;Software Design II C+ Strings15 02 August 2024Range-checkinglRange-checkings3.at( index );ReturnscharacteratindexindexCanthrowanout_of_rangeout_of_rangeexceptionhasnorangechecking#include
13、.strings s=leon;trycharletter=s s.at( 50);coutletteris=letterendl;catch(exception&e)coutout_of_rangeexception:e.what()what()endl;Software Design II C+ Strings16 02 August 2024Concatenationl lConcatenationConcatenations3.append( pet );s3 += pet;Bothaddpettoendofs3s3.append( s1, start, N );AppendsN Nc
14、haractersfroms1s1,beginningatindexstartstartSoftware Design II C+ Strings17 02 August 2024Comparing stringslOverloadedoperators=,!=,=pare(s2)returnspositiveifs1 islexicographicallygreatercomparesletterbyletterBlexicographicallygreaterthanAa lexicographicallygreaterthanAa lexicographicallygreaterthan
15、Zreturnsnegativeifless;zeroifequalSample order: A,”Apple”, “Banana”, “Zest”, a, “apricot”, “leon”pare(start, length, s2, start, length)Cpare(start, length, s2)Compareportionofs1withallofs2Software Design II C+ Strings18 02 August 2024SubstringslFunctionsubstrgetsasubstrings1.substr( start, N );getsN
16、characters,beginningwithindex startreturnssubstringSoftware Design II C+ Strings19 02 August 2024Swapping stringsls1.swap(s2);SwitchcontentsoftwostringsSoftware Design II C+ Strings20 02 August 2024string CharacteristicslMemberfunctionss1.size() ands1.length()Numberofcharactersinastrings1.capacity()
17、Numberofelementsthatcanbestoredwithoutreallocation编译器为string预分配内存的大小s1.max_size()Maximumpossiblestringsizes1.empty()Returnstrueifemptys1.resize(newlength)ResizesstringtonewlengthSoftware Design II C+ Strings21 02 August 2024Finding Strings and Characters in a stringl lFind functionsFind functionsIff
18、ound,indexreturnedIfnotfound,string:nposreturnedPublicstaticconstantinclassstrings1.find( s2 )s1.rfind( s2 )Searchesright-to-lefts1.find_first_of( s2 )Returnsfirstoccurrenceofanycharacterins2Example: s1.find_first_of( abcd )Returnsindexoffirsta,b,cordSoftware Design II C+ Strings22 02 August 2024Fin
19、ding Strings and Characters in a stringl lFind functionsFind functionss1.find_last_of( s2 )Findslastoccurrenceofanycharacterins2s1.find_first_not_of( s2 )FindsfirstcharacterNOTins2s1.find_last_not_of( s2 )FindslastcharacterNOTins2Software Design II C+ Strings23 02 August 2024Replacing Characters in
20、a stringls1.erase( start )Erasefromindexstarttoendofstring,includingstartlReplaces1.replace( begin, N, s2)begin:indexins1tostartreplacingN:numberofcharacterstoreplaces2:replacementstrings1.replace( begin, N, s2, index, num )index:elementins2wherereplacementcomesfromnum:numberofelementstousewhenrepla
21、cingReplacecanoverwritecharactersSoftware Design II C+ Strings24 02 August 2024Examples1.replace( begin, N, s2, index, num )begin:indexins1tostartreplacingN:numberofcharacterstoreplaces2:replacementstringindex:elementins2wherereplacementcomesfromnum:numberofelementstousewhenreplacingstringstr=thisis
22、anexamplestring. .;stringstr3=samplephrase;strstr.replace(19,6,.replace(19,6,str3str3,7,6);,7,6);/thisisanexamplephrase. Software Design II C+ Strings25 02 August 2024Inserting Characters into a stringls1.insert( index, s2 )Insertss2beforepositionindexls1.insert( index, s2, index2, N );Insertssubstr
23、ingofs2beforepositionindexSubstringisNcharacters,startingatindex2Software Design II C+ Strings26 02 August 2024Conversion to C-Style char*lConversion functionsStringsarenotnecessarilynull-terminateds1.copy( ptr, N, index )CopiesNcharactersintothearrayptrStartsatlocationindexNeedtonullterminatecharst
24、r8;strings2=cathode;s2.copy(str, 5, 2); /copy5charactersintostr/startingatindex2/strcat(str,0);/doesnotworkstr5 = 0; /thisisrequiredcoutstr=strendl;couts2=s2endl;Output:str=thodes2=cathodeSoftware Design II C+ Strings27 02 August 2024Conversion to C-Style char * StringslConversion functionss1.c_str(
25、)Returnsconst char *Nullterminatede.g. Usefulforfilenames:ifstreamin(s1.c_str();s1.data()Returnsconst char *NOTnull-terminatedSoftware Design II C+ Strings28 02 August 2024Warning!l lNoconversionNoconversionfromintorcharThefollowingdefinitionscouldreturnerrors,orwarningsonly,butthenwouldcausetheprog
26、ramtocrashafterwardsstring error1 = c;string error2( u );string error3 = 22;string error4( 8 ); However,itcanbeassignedonecharafteritsdeclaration:s = n;Software Design II C+ Strings29 02 August 2024String Stream ProcessinglI/OofstringstoandfrommemoryCalledin-memoryI/OorstringstreamprocessingClassesi
27、stringstream/inputfromstringostringstream/outputtoastringstringstream( string ) /mostusefulRequires andheadersUsestringformattingtosavedatatomemoryallowsastringtobeusedasaninternalfileusefulforbufferinginputandoutputSoftware Design II C+ Strings30 02 August 2024Serves as a conduit to an anonymous st
28、ring which can be readwith 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 word m y; s = iss.str(); cout endl s endl; cout word = word endl; cout m = m endl; cout y = y endl;iss is
29、defined and bound to bufferContentsofbuffercanbeaccessedaselementsofastring,orbyformattedinputthroughtheissobject.Input String StreamSoftware Design II C+ Strings32 02 August 2024#include #include #include #include #include using namespace std;int main() string s1(mydata.txt); ifstream in( s1.c_str(
30、) ); char buffer1024; while( in.getline( buffer, 1024 ) ) string stemp( buffer ); cout Line is: stemp d1 d2; cout d1 , d2 endl; cout endl; in.close(); return 0;UsingstringexamplelInput file:1.0 2.01.0 2.01.1 2.41.1 2.41.8 2.81.8 2.8# #1.34 2.991.34 2.991.4 8.991.4 8.99lExample Output:Line is:1.0 2.0
31、Line is:1.0 2.01,21,2Line is:1.1 2.4Line is:1.1 2.41.1,2.41.1,2.4Line is:1.8 2.8Line is:1.8 2.81.8,2.81.8,2.8Line is:#1.34 2.99Line is:#1.34 2.99Line is:1.4 8.99Line is:1.4 8.991.4,8.991.4,8.99Software Design II C+ Strings33 02 August 2024#include #include #include #include #include using namespace
32、std;int main() string s1(mydata.txt); ifstream in( s1.c_str() ); char buffer1024; while( in.getline( buffer, 1024 ) ) string stemp( buffer ); cout Line is: stemp 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; whil
33、e(getline( in, buffer ) ) cout Line is: buffer d1 d2; cout data: d1 , d2 endl; cout endl; in.close(); return 0;Alternatively: (no C-style char*)Software Design II C+ Strings34 02 August 2024SummaryC+ strings are safer and easier to use than C string.Next TemplatesSoftware Design II C+ Strings35 02 A
34、ugust 2024MethodUseappend(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, chars or other string objects.at(s
35、ize_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
36、 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
37、, size_t count);Erases characters from the specified positions.Software Design II C+ Strings36 02 August 2024MethodUsefind(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,
38、 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
39、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
40、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,
41、 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+ Strings37 02 August 2024Thank you!