版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Chapter 8Strings and Vectors Overview8.1 An Array Type for Strings 8.2 The Standard string Class8.3 VectorsSlide 8- 38.1An Array Type for StringsAn Array Type for StringsC-strings can be used to represent strings of charactersC-strings are stored as arrays of charactersC-strings use the null charact
2、er 0 to end a stringThe Null character is a single characterTo declare a C-string variable, declare an array of characters: char s11;Slide 8- 5C-string Detailss0s1s2s3s4s5s6s7s8s9HiMom!0?Slide 8- 6Declaring a C-string as char s10 creates spacefor only nine charactersThe null character terminator req
3、uires one spaceA C-string variable does not need a size variableThe null character immediately follows the lastcharacter of the stringExample: C-string DeclarationTo declare a C-string variable, use the syntax:char Array_name Maximum_cString_Size + 1;+ 1 reserves the additional character needed by 0
4、Slide 8- 7Initializing a C-stringTo initialize a C-string during declaration: char myMessage20 = Hi there.;The null character 0 is added for youAnother alternative: char shortString = abc; but not this: char shortString = a, b, c; Slide 8- 8C-string errorThis attempt to initialize a C-string does no
5、t cause the 0 to be inserted in the arraychar shortString = a, b, c;Slide 8- 9Dont Change 0Do not to replace the null character whenmanipulating indexed variables in a C-stringIf the null character is lost, the array cannot act like a C-stringExample: int index = 0; while (ourStringindex != 0) ourSt
6、ringindex = X; index+; This code depends on finding the null character!Slide 8- 10Safer Processing of C-stringsThe loop on the previous slide depended on finding the 0 characterIt would be wiser to use this version in case the 0 character had been removed int index = 0; while (ourStringindex != 0 &
7、index SIZE) ourStringindex = X; index+; Slide 8- 11Assignment With C-stringsThis statement is illegal: aString = Hello;This is an assignment statement, not an initializationThe assignment operator does not work with C-stringsSlide 8- 12Assignment of C-stringsA common method to assign a value to a C-
8、string variable is to use strcpy, defined in the cstring libraryExample: #include char aString 11; strcpy (aString, Hello);Places Hello followed by the null character in aStringSlide 8- 13A Problem With strcpystrcpy can create problems if not used carefullystrcpy does not check the declared length o
9、f the first argumentIt is possible for strcpy to write characters beyond the declared size of the arraySlide 8- 14A Solution for strcpyMany versions of C+ have a safer version of strcpy named strncpystrncpy uses a third argument representing the maximum number of characters to copyExample: char anot
10、herString10; strncpy(anotherString, aStringVariable, 9);This code copies up to 9 characters into anotherString, leaving one space for 0Slide 8- 15= Alternative for C-stringsThe = operator does not work as expected withC-stringsThe predefined function strcmp is used to compare C-string variablesExamp
11、le: #include if (strcmp(cString1, cString2) cout Strings are not the same.; else cout String are the same.;Slide 8- 16strcmps logic strcmp compares the numeric codes of elementsin the C-strings a character at a timeIf the two C-strings are the same, strcmp returns 00 is interpreted as falseAs soon a
12、s the characters do not matchstrcmp returns a negative value if the numeric code in the first parameter is lessstrcmp returns a positive value if the numeric code in the second parameter is lessNon-zero values are interpreted as trueSlide 8- 17More C-string FunctionsThe cstring library includes othe
13、r functionsstrlen returns the number of characters in a string int x = strlen( aString);strcat concatenates two C-stringsThe second argument is added to the end of the firstThe result is placed in the first argumentExample: char stringVar20 = The rain; strcat(stringVar, in Spain); Now stringVar cont
14、ains The rainin SpainSlide 8- 18The strncat Functionstrncat is a safer version of strcatA third parameter specifies a limit for the number of characters to concatenateExample:char stringVar20 = The rain; strncat(stringVar, in Spain, 11);Slide 8- 19Display 8.1 (1)Display 8.1 (2)C-strings as Arguments
15、 and ParametersC-string variables are arraysC-string arguments and parameters are used just like arraysIf a function changes the value of a C-string parameter, it is best to include a parameter for the declared size of the C-stringIf a function does not change the value of a C-string parameter, the
16、null character can detect the end of the string and no size argument is neededSlide 8- 20C-string OutputC-strings can be output with the insertion operatorExample: char news = C-strings; cout news Wow. can fill a C-string Whitespace ends reading of data Example: char a80, b80; cout Enter input: a b;
17、 cout a b End of Output;could produce: Enter input: Do be do to you! DobeEnd of OutputSlide 8- 22Reading an Entire LinePredefined member function getline can read anentire line, including spacesgetline is a member of all input streamsgetline has two argumentsThe first is a C-string variable to recei
18、ve inputThe second is an integer, usually the size of the first argument specifying the maximum number of elements in the first argument getline is allowed to fillSlide 8- 23Using getlineThe following code is used to read an entire lineincluding spaces into a single C-string variable char a80;cout E
19、nter input:n;cin.getline(a, 80);cout a cString; inStream.getline(cString, 80);Replace cout with the name of an output-file stream out_stream cString; Slide 8- 26getline syntaxSyntax for using getline is cin.getline(String_Var, Max_Characters + 1);cin can be replaced by any input streamMax_Characters
20、 + 1 reserves one element for the null characterSlide 8- 27C-String to Numbers1234 is a string of characters1234 is a numberWhen doing numeric input, it is useful to read input as a string of characters, then convert the string to a numberReading money may involve a dollar sign Reading percentages m
21、ay involve a percent signSlide 8- 28C-strings to IntegersTo read an integer as charactersRead input as characters into a C-string, removing unwanted charactersUse the predefined function atoi to convert the C-string to an int valueExample: atoi(1234) returns the integer 1234 atoi(#123) returns 0 bec
22、ause # is not a digitSlide 8- 29C-string to longLarger integers can be converted using the predefined function atolatol returns a value of type longSlide 8- 30C-string to doubleC-strings can be converted to type double usingthe predefined function atofatof returns a value of type doubleExample: atof
23、(9.99) returns 9.99 atof($9.99) returns 0.0 because the $ is not a digitSlide 8- 31Library cstdlibThe conversion functions atoi atolatofare found in the library cstdlibTo use the functions use the include directive #include Slide 8- 32Numeric InputWe now know how to convert C-strings to numbersHow d
24、o we read the input?Function readAndClean, in Display 8.2Reads a line of inputDiscards all characters other than the digits 0 through 9Uses atoi to convert the cleaned-up C-string to intSlide 8- 33Display 8.2 (1)Display 8.2 (2)Confirming InputFunction get_int, from Display 8.3Uses readAndClean to re
25、ad the users inputAllows the user to reenter the input until the user is satisfied with the number computed from the input stringSlide 8- 34Display 8.3 (1)Display 8.3 (2)Section 8.1 ConclusionCan youDescribe the benefits of reading numeric data as characters before converting the characters to a num
26、ber?Write code to do input and output with C-strings?Use the atoi, atol, and atof functions?Identify the character that ends a C-string?Slide 8- 358.2The Standard string ClassThe Standard string ClassThe string class allows the programmer to treatstrings as a basic data typeNo need to deal with the
27、implementation as with C-stringsThe string class is defined in the string libraryand the names are in the standard namespaceTo use the string class you need these lines: #include using namespace std;Slide 8- 37Assignment of StringsVariables of type string can be assigned withthe = operatorExample: s
28、tring s1, s2, s3; s3 = s2;Quoted strings are type cast to type stringExample: string s1 = Hello Mom!;Slide 8- 38Using + With stringsVariables of type string can be concatenated with the + operatorExample: string s1, s2, s3; s3 = s1 + s2;If s3 is not large enough to contain s1 + s2, more space is all
29、ocatedSlide 8- 39string ConstructorsThe default string constructor initializes the string to the empty stringAnother string constructor takes a C-string argumentExample: string phrase; / empty string string noun(ants); / a string version / of antsSlide 8- 40Mixing strings and C-stringsIt is natural
30、to work with strings in the followingmanner string phrase = I love + adjective + + noun + !;It is not so easy for C+! It must either convert the null-terminated C-strings, such as I love, to strings, or it must use an overloaded + operator that works with strings and C-stringsSlide 8- 41Display 8.4I
31、/O With Class stringThe insertion operator is used to output objects of type stringExample: string s = Hello Mom!; cout can be used to input data for objects of type stringExample: string s1; cin s1; skips whitespace and stops on encountering more whitespaceSlide 8- 42getline and Type stringA getlin
32、e function exists to read entire lines intoa string variableThis version of getline is not a member of the istream class, it is a non-member functionSyntax for using this getline is different than that used with cin: cin.getline()Syntax for using getline with string objects: getline(Istream_Object,
33、String_Object);Slide 8- 43getline ExampleThis code demonstrates the use of getline withstring objects string line;cout Enter a line of input:n;getline(cin, line);cout line END OF OUTPUTn;Output could be: Enter some input: Do be do to you! Do be do to you!END OF OUTPUTSlide 8- 44Character Input With
34、stringsThe extraction operator cannot be used to reada blank characterTo read one character at a time remember to use cin.getcin.get reads values of type char, not type stringThe use of getline, and cin.get for string input are demonstrated in Slide 8- 45Display 8.5 (1)Display 8.5 (2)Another Version
35、 of getlineThe versions of getline we have seen, stop reading at the end of line marker ngetline can stop reading at a character specified in the argument listThis code stops reading when a ? is read string line; cout s2; cin s2;Slide 8- 47returnsgetline DeclarationsThese are the declarations of the
36、 versions of getline for string objects we have seenistream& getline(istream& ins, string& strVar, char delimiter);istream& getline(istream& ins, string& strVar);Slide 8- 48Mixing cin and getlineRecall cin n skips whitespace to find what it is to read then stops reading when whitespace is foundcin l
37、eaves the n character in the input streamExample: int n; string line; cin n; getline(cin, line);leaves the n which immediately ends getlines readingline is set equal to the empty stringSlide 8- 49ignore ignore is a member of the istream classignore can be used to read and discard all the characters,
38、 including n that remain in a lineIgnore takes two argumentsFirst, the maximum number of characters to discardSecond, the character that stops reading and discardingExample: cin.ignore(1000, n); reads up to 1000 characters or to n Slide 8- 50String ProcessingThe string class allows the same operatio
39、ns we used with C-stringsand moreCharacters in a string object can be accessed as if they are in an arraylast_namei provides access to a single characteras in an arrayIndex values are not checked for validity!Slide 8- 51Display 8.6Member Function lengthThe string class member function length returns
40、 the number of characters in the string object:Example: int n = stringVar.length( );Slide 8- 52Member Function atat is an alternative to using s to access characters in a string.at checks for valid index valuesExample: string str(Mary); cout str6 endl; cout str.at(6) endl; str2 = X; str.at(2) = X;Sl
41、ide 8- 53EquivalentEquivalentOther string class functions are found in Display 8.7string class to numbersC+11 has new functions to convert a string class object to a numberint i;double d;string s;i = stoi(35); / Converts the string 35 to an integer 35d = stod(2.5); / Converts the string 2.5 to the d
42、ouble 2.5C+11 has new functions to convert a string class object to a numberstring s = to_string(1.2*2); / “2.4” stored in sSlide 1- 54Comparison of stringsComparison operators work with string objectsObjects are compared using lexicographic order (Alphabetical ordering using the order of symbols in
43、 the ASCII character set.) = returns true if two string objects contain the same characters in the same orderRemember strcmp for C-strings?, = can be used to compare string objectsSlide 8- 55Program Example:Palindrome TestingA palindrome is a string that reads the same from front to back as it does
44、from back to frontThis program ignores spaces and punctuationUpper and lowercase versions of letters are considered the same letterExamples: Able was I ere I saw Elba. Madam, Im Adam. A man, a plan, a canal, Panama. RacecarSlide 8- 56Palindrome Testing:removePunctremovePunct removes punctuation from
45、 a stringremovePunct compares each character in the string to the characters in a string containing all the punctuation characters and the space character. If a match is not found, the character is added to the string noPunctnoPunct, the original string less any punctuation or spaces, is returnedSli
46、de 8- 57Palindrome Testing:substrThe substr member function is used to locate a substring within a stringremovePunct uses substr to extract a singlecharacter at a time from the source string. The character is stored in aChar.removePunct then uses function find to see if the character in aChar is in
47、the string of punctuation charactersSlide 8- 58Palindrome Testing:The ProgramThe entire palindrome testing program is found in Slide 8- 59Display 8.8 (1)Display 8.8 (2)Display 8.8 (4)Display 8.8 (3)string Objects to C-stringsRecall the automatic conversion from C-stringto string: char aCString = C-s
48、tring; stringVariable = aCString;strings are not converted to C-stringsBoth of these statements are illegal:aCString = stringVariable;strcpy(aCString, stringVariable);Slide 8- 60Converting strings to C-stringsThe string class member function c_str returnsthe C-string version of a string objectExampl
49、e: strcpy(aCString, stringVariable.c_str( ) ); This line is still illegal aCString = stringVariable.c_str( ) ;Recall that operator = does not work with C-stringsSlide 8- 61Section 8.2 ConclusionCan youShow how a string object can be used like a C-string?Write code to read an entire line into a strin
50、g object?Use the string function at to access individual characters in a string object?Write code to convert a string to a C-string?Slide 8- 628.3VectorsVectorsVectors are like arrays that can change size asyour program runsVectors, like arrays, have a base typeTo declare an empty vector with base t
51、ype int: vector v; identifies vector as a template class You can use any base type in a template class: vector v;Slide 8- 64Accessing vector ElementsVectors elements are indexed starting with 0 s are used to read or change the value of an item: vi = 42; cout vi; s cannot be used to initialize a vect
52、or elementSlide 8- 65Initializing vector ElementsElements are added to a vector using the member function push_backpush_back adds an element in the next available positionExample: vector sample; sample.push_back(0.0); sample.push_back(1.1); sample.push_back(2.2);Slide 8- 66The size Of A vectorThe me
53、mber function size returns the number of elements in a vectorExample: To print each element of a vector given the previous vector initialization: for (int i= 0; i sample.size( ); i+) cout samplei endl;Slide 8- 67The Type unsigned intThe vector class member function size returns an unsigned int Unsig
54、ned ints are nonnegative integersSome compilers will give a warning if the previous for-loop is not changed to: for (unsigned int i= 0; i sample.size( ); i+) cout samplei endl;Slide 8- 68Alternate vector InitializationA vector constructor exists that takes an integer argument and initializes that nu
55、mber of elements Example: vector v(10); initializes the first 10 elements to 0 v.size( ) would return 10 s can now be used to assign elements 0 through 9push_back is used to assign elements greater than 9Slide 8- 69Vector Initialization With ClassesThe vector constructor with an integer argumentInitializes elements of number types to zeroInitializes elements of class types using the default constructor for the classSlide 8- 70The vector LibraryTo use the vector classInclude the vector library #include Vector names are placed in the standard namespace so the usual using
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 拆船业的可持续发展战略规划考核试卷
- 制鞋业市场产品差异化考核试卷
- 木材的电子与通讯应用考核试卷
- 福建省福州市福清市2024-2025学年六年级上学期期中英语试卷
- 企业知识产权培训方案
- 化学纤维在水利工程领域的应用考核试卷
- 煤矿安全管理与风险预控考核试卷
- 低温低价设备制造技术在铁合金冶炼中的应用考核试卷
- 城市交通管理的案例分析考核试卷
- 2025年中考语文备考之名著复习:《艾青诗选》题集组(答案)
- 原油电脱盐电脱水技术
- 小学生劳动教育评价细则
- 专业工程分包业主审批表
- XX公司员工跟投管理办法
- 道路运输安全事故报告、统计与调查处理制度
- 甘肃广播电视大学钢结构(本)不计分-3.3小测验答案
- 人员密集场所火灾疏散应急预案(精选14篇)
- 不合理处方登记表
- 养老机构护理管理制度与规范
- 国内外利用活性炭处理硫化氢的原理
- 京津冀异地就医直接结算政策
评论
0/150
提交评论