数据结构与程序设计(17)String-Operator-overload_第1页
数据结构与程序设计(17)String-Operator-overload_第2页
数据结构与程序设计(17)String-Operator-overload_第3页
数据结构与程序设计(17)String-Operator-overload_第4页
数据结构与程序设计(17)String-Operator-overload_第5页
已阅读5页,还剩29页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1/21/2026数据结构与程序设计1课程内容安排CString与String的比较。讨论C++中StringClass的实现方法。1/21/2026数据结构与程序设计2CString与StringClassstringclass:stringclassinthestandardlibraryaccessedby#include<string>Cstrings:canbeaccessedby#include<cstring>

AStringconstantisstoredasachararray.即一个常量的string被认为是cstringe.g.:“Helloeveryone”//cstringstrings=“Helloeveryone”//Stringobject

1/21/2026数据结构与程序设计3WhatisaCString?ChararrayACstringisachararrayterminatedbythenullcharacter‘\0’(withASCIIvalue0).ACstringvariablecanbeinitializedinitsdeclarationinfollowingways.

charmessage[8]={‘H’,‘e’,‘l’,‘l’,‘o’,‘\0’};

charmessage[8]=“Hello”;Char*message=“hello”;message[0][1][2][3][4][5][6][7]‘H’‘e’‘l’‘l’‘o’‘\0’1/21/2026数据结构与程序设计4字符串(String)字符串是n(0)个字符的有限序列,记作S:“c1c2c3…cn”其中,S是串名字

“c1c2c3…cn”

是串值

ci是串中字符

n是串的长度。

1/21/2026数据结构与程序设计5functionsthatmanipulateC-strings//字符串的拷贝操作。char*strcpy(char*to,char*from);Pre:Thestringfromhasbeeninitialized.Post:Thefunctioncopiesstringfromtostringto,including‘\0’;itreturnsapointertothebeginningofthestringto.//将from指向的内容链接在to的内容之后char*strcat(char*to,char*from);Pre:Thestringsfromandtohavebeeninitialized.Post:Thefunctioncopiesstringfromtotheendofstringto,including‘\0’;itreturnsapointertothebeginningofthestringto.1/21/2026数据结构与程序设计6functionsthatmanipulateC-strings//求字符串的长度intstrlen(char*s);Pre:Thestringshasbeeninitialized.Post:Thefunctionreturnsthelengthofthestrings,notincludingthenullbyte‘\0’attheendofthestrings.//字符串的比较操作。intstrcmp(char*s1,char*s2);Pre:Thestringss1ands2havebeeninitialized.Post:Thefunctioncomparesstrings1tostrings2;itreturns<0ifs1<s2,0ifs1==s2,or>0ifs1>s2.1/21/2026数据结构与程序设计7functionsthatmanipulateC-strings//返回s2第一次在s1中出现的位置。char*strstr(char*s1,char*s2);Pre:Thestringss1ands2havebeeninitialized.Post:Thefunctionreturnsapointertothefirstoccurrenceofthestrings2inthestrings1,oritreturnsNULLifthestrings2isnotpresentins1.1/21/2026数据结构与程序设计8StringsinC char*p="helloworld";//can'tbewritten char*q=newchar[strlen(p)+1]; strcpy(q,p); cout<<q<<endl; //q=p; p=q; *p='H';cout<<q<<endl; cout<<p<<endl;1/21/2026数据结构与程序设计9StringsinCchar*strcpy(char*to,char*from){ inti; for(i=0;from[i]!='\0';i++)to[i]=from[i]; to[i]='\0'; returnto;}1/21/2026数据结构与程序设计10StringsinCintstrlen(char*s){inti;for(i=0;s[i]!='\0';i++);return(i);}1/21/2026数据结构与程序设计11ComparisonBOOKP234Figure6.5“Importantstring”“acquiresanalias”S2=s1S2S11/21/2026数据结构与程序设计12ComparisonC-stringsarewidelyavailable.C-stringsareveryefficient.C-stringobjectsarenotencapsulated.C-stringsareeasytomisuse,withconsequencesthatcanbedisastrous.ItiseasyforaclienttocreateeithergarbageoraliasesforC-stringdata.1/21/2026数据结构与程序设计13//******************************************************//PrintNameprogram//Thisprogramprintsanameintwodifferentformats//******************************************************#include<iostream> //forcoutandendl#include<string> //fordatatypestringusingnamespacestd;conststringFIRST=“Herman”;//Person’sfirstnameconststringLAST=“Smith”;//Person’slastnameconstcharMIDDLE=‘G’;//Person’smiddleinitialC++Program--STLSTRING1/21/2026数据结构与程序设计14C++CodeContinuedintmain(){stringfirstLast;//Nameinfirst-lastformatstringlastFirst; //Nameinlast-firstformat

firstLast=FIRST+““+LAST;cout<<“Nameinfirst-lastformatis“<<endl <<firstLast<<endl;lastFirst=LAST+“,“+FIRST+’’;cout<<“Nameinfirst-lastformatis“<<endl <<lastFirst<<MIDDLE<<’.’<<endl;return0;}1/21/2026数据结构与程序设计15OutputofProgram

Nameinfirst-lastformatisHermanSmithNameinlast-first-initialformatisSmith,HermanG.1/21/2026数据结构与程序设计16ImplementationofStringClassclassString{public://methodsofthestringADT String(); ~String(); String(constString©);//copyconstructor String(constchar*copy);//conversionfromC-string String(List<char>©);//conversionfromList voidoperator=(constString©); constchar*c_str()const;//conversiontoC-stylestringprotected: char*entries; intlength;};1/21/2026数据结构与程序设计17运算符重载,全局方法booloperator==(constString&rst,constString&second);booloperator>(constString&rst,constString&second);booloperator<(constString&rst,constString&second);booloperator>=(constString&rst,constString&second);booloperator<=(constString&rst,constString&second);booloperator!=(constString&rst,constString&second);1/21/2026数据结构与程序设计18StringconstructorString::String(){ entries=newchar[1]; entries[0]='\0'; length=0;}1/21/2026数据结构与程序设计19StringconstructorString::String(List<char>&in_list)/*Post:TheStringisinitializedbythecharacterListin_list.*/{ length=in_list.size(); entries=newchar[length+1]; for(inti=0;i<length;i++)in_list.retrieve(i,entries[i]); entries[length]='\0';}1/21/2026数据结构与程序设计20ImplementationofStringClassconstchar*String::c_str()const/*Post:ApointertoalegalC-stringobjectmatchingtheStringisreturned.*/{ return(constchar*)entries;}1/21/2026数据结构与程序设计21全局函数的实现

OperatorOverloadbooloperator==(constString&first,constString&second)/*Post:ReturntrueiftheStringfirstagreeswithStringsecond.Else:Returnfalse.*/{ returnstrcmp(first.c_str(),second.c_str())==0;}1/21/2026数据结构与程序设计22FunctionOverloadvoidstrcat(String&add_to,constString&add_on)/*Post:ThefunctionconcatenatesStringadd_onontotheendofStringadd_to.*/{constchar*cfirst=add_to.c_str();constchar*csecond=add_on.c_str();char*copy=newchar[strlen(cfirst)+strlen(csecond)+1];strcpy(copy,cfirst);strcat(copy,csecond);add_to=copy;//?delete[]copy;}1/21/2026数据结构与程序设计23MainProgramStringread_in(istream&input)/*Post:ReturnaStringread(ascharactersterminatedbyanewlineoranend-of-filecharacter)fromanistreamparameter.*/{List<char>temp;intsize=0;charc;while((c=input.peek())!=EOF&&(c=input.get())!='\n')temp.insert(size++,c);Stringanswer(temp);returnanswer;}1/21/2026数据结构与程序设计24MainProgramvoidwrite(String&s)/*Post:TheStringparametersiswrittentocout.*/{cout<<s.c_str()<<endl;}注意:Char*p=“hello”;Cout<<p;//将输出字符串hello的值。1/21/2026数据结构与程序设计25MainProgramostream&operator<<(ostream&output,Strings1){ ou

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论