用思维导图和实例学习C 之一 字符串处理.doc

上传人:本田雅阁 文档编号:2786234 上传时间:2019-05-16 格式:DOC 页数:14 大小:51.43KB
返回 下载 相关 举报
用思维导图和实例学习C 之一 字符串处理.doc_第1页
第1页 / 共14页
用思维导图和实例学习C 之一 字符串处理.doc_第2页
第2页 / 共14页
用思维导图和实例学习C 之一 字符串处理.doc_第3页
第3页 / 共14页
用思维导图和实例学习C 之一 字符串处理.doc_第4页
第4页 / 共14页
用思维导图和实例学习C 之一 字符串处理.doc_第5页
第5页 / 共14页
点击查看更多>>
资源描述

《用思维导图和实例学习C 之一 字符串处理.doc》由会员分享,可在线阅读,更多相关《用思维导图和实例学习C 之一 字符串处理.doc(14页珍藏版)》请在三一文库上搜索。

1、用思维导图和实例学习C 之一 字符串处理1.本章思维导图:Example1:char*strcpy(char*target,const char*source)char*t=target;/Copy the contents of source into target.while(*source)*target+=*source+;/Null-terminate the target.*target=message;/Return pointer to the start of target.return t;Example2:void*memmove(void*target,const vo

2、id*source,size_t count)这个函数即使是在源和目的字符串有所重叠时操作也能成功,虽然source为const,但是其指向的array也可能被修改。2.C型字符串操作实例:Ex1.基本操作/*=*Filename:2-1.cpp*Description:Fundamental Operations in CType String*Version:1.0*Created:05/11/2010 10:43:11 AM*Revision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#include usin

3、g namespace std;int main(int argc,char*argv)char strA7=UP;char strB5=DOWN;char strC5=LEFT;char strD6=RIGHT;/*Display*/coutHere are the strings:endl;coutstrA:strA endl;coutstrB:strB endl;coutstrC:strC endl;coutstrD:strDnn;/Display the length of strA.coutLength of strA isstrlen(strA)endl;coutSize of s

4、trA issizeof(strA)endl;/Concatenate strB with strA coutThe result of Concatenate is strA:/Copy strC into strB,and partially strD into strA coutThe result of Copy is:coutThe result of partially Copy is strA:/Compare strC with strB if(!strcmp(strC,strB)coutstrC is equal to strB!if(!strncmp(strD,strA,3

5、)coutstrD is equal to strA partially!return 0;Ex2.搜索匹配相关操作/*=*Filename:2-2.cpp*Description:Search Operation in Ctype String*Version:1.0*Created:05/11/2010 11:38:15 AM*Revision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#include using namespace std;int main(void)const char*url=HerbS;

6、const char*url2=Apache.org;const char*emailaddr=HerbHerbS;const char*tld=.com,.net,.org;const char*p;/First,determine if url and url2 ,.net,or.org.for(int i=0;i 3;i+)p=strstr(url,tldi);if(p)cout urlhas top-level domaintldiendl;p=strstr(url2,tldi);if(p)cout url2has top-level domaintldiendl;/Search fo

7、r aspecific character.p=strchr(emailaddr,);if(p)coutSite name of e-mail address is:p+1 endl;/Search for any of aset of characters.In this case,/find the firstor period.p=strpbrk(emailaddr,.);if(p)coutFound*p endl;/Search for the beginning if(strspn(url2,Apache)=6)coutUrl2 begins with theApacheendl;/

8、与strchr正好倒过来if(p=strrchr(emailaddr,b)cout pendl;return 0;Ex3.倒置一个字符串我们用了四种方法,最后一种方法经常在面试笔试题中出现。/*=*Filename:2-3.cpp*Description:Reverse astring*Version:1.0*Created:05/12/2010 03:08:09 PM*Revision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#include using namespace std;void revstr(cha

9、r*str);void revstr_p(char*str);void revstr_recursive(char*str,int start,int end);char*(revstrcpy)(char*rstr,const char*orgstr);int main()char str=abcdefghijklmnopqrstuvwxyz;char*des=new char27;coutOriginal string:str endl;revstr(str);coutReversed string:str endl;revstr_p(str);coutReversed string usi

10、ng pointer:str endl;revstr_recursive(str,0,strlen(str)-1);coutReversed string using recursive:str endl;coutReversed string using copy method:revstrcpy(des,str)endl;return 0;void revstr(char*str)int i,j;char t;for(i=0,j=strlen(str)-1;i j;+i,-j)t=stri;stri=strj;strj=t;/Reverse astring in place.Use poi

11、nters rather than array indexing.void revstr_p(char*str)char t;char*inc_p=str;char*dec_p=&strstrlen(str)-1;while(inc_p=dec_p)t=*inc_p;*inc_p+=*dec_p;*dec_p-=t;void revstr_recursive(char*str,int start,int end)if(start end)revstr_recursive(str,start+1,end-1);else return;char t=strstart;strstart=strend

12、;strend=t;char*(revstrcpy)(char*rstr,const char*orgstr)/返回rstr的原始值使函数能够支持链式表达式,增加了函数的附加值。同样功能的函数,如果能合理地提高的可用性,自然就更加理想。if(rstr=NULL)|(orgstr=NULL)throwInvalid argument(s);char*dst=rstr;dst+=strlen(orgstr);*dst-=message;while(*orgstr)*dst-=*orgstr+;return rstr;Ex4.忽略大小写的字符串比较/*=*Filename:2-4.cpp*Descr

13、iption:Ignore the Letter case when compared*Version:1.0*Created:05/12/2010 03:44:34 PM*Revision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#include using namespace std;int strcmp_ign_case(const char*str1,const char*str2);int main(void)char strA=tesT;char strB=Test;char strC=testing;

14、char strD=Tea;int result;coutHere are the strings:endl;coutstrA:strA endl;coutstrB:strB endl;coutstrC:strC endl;coutstrD:strDnn;/Compare strings ignoring case.result=strcmp_ign_case(strA,strB);result=strcmp_ign_case(strA,strC);result=strcmp_ign_case(strA,strD);result=strcmp_ign_case(strD,strA);retur

15、n 0;/A simple string comparison function that ignores case differences.int strcmp_ign_case(const char*str1,const char*str2)const char*str1_cp=str1;const char*str2_cp=str2;while(*str1_cp&*str2_cp)if(tolower(*str1_cp+)!=tolower(*str2_cp+)break;int result=tolower(*str1_cp)-tolower(*str2_cp);cout str1is

16、;if(!result)coutequal to;else if(result 0)coutless than;else coutgreater than;cout str2 endl;return result;Ex5.搜索替换/*=*Filename:2-5.cpp*Description:Replace the sub_str with another str*Version:1.0*Created:05/12/2010 04:07:02 PM*Revision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#in

17、clude#include using namespace std;bool search_and_replace(char*orgstr,int maxlen,const char*oldsubstr,const char*newsubstr);char*search_and_replace_alloc(const char*str,const char*oldsubstr,const char*newsubstr)throw(bad_alloc);int main(void)char str80=alpha beta gamma alpha beta gamma;char*ptr=NULL

18、;coutOriginal string:strnn;coutFirst,replace all instances of alpha with epsilon.n;/Replace all occurrences of alpha with epsilon.while(search_and_replace(str,sizeof(str),alpha,epsilon)coutAfter areplacement:str endl;coutSecond,replace one instances of epsilon with alpha.n;tryptr=search_and_replace_

19、alloc(str,epsilon,alpha);catch(bad_alloc exc)/Take appropriate action here.if(ptr)coutAfter areplacement:ptr endl;delete ptr;return 0;bool search_and_replace(char*orgstr,int maxlen,const char*oldsubstr,const char*newsubstr)char*pos=NULL;if(orgstr=NULL)|(oldsubstr=NULL)|(newsubstr=NULL)return false;i

20、nt len=strlen(orgstr)-strlen(oldsubstr)+strlen(newsubstr);if(len maxlen)return false;if(pos=strstr(orgstr,oldsubstr)memmove(pos+strlen(newsubstr),pos+strlen(oldsubstr),strlen(pos)-strlen(oldsubstr)+1);strncpy(pos,newsubstr,strlen(newsubstr);return true;elsereturn false;char*search_and_replace_alloc(

21、const char*str,const char*oldsubstr,const char*newsubstr)throw(bad_alloc)const char*pos=NULL;if(str=NULL)|(oldsubstr=NULL)|(newsubstr=NULL)return NULL;int size=strlen(str)+strlen(newsubstr)-strlen(oldsubstr)+1;char*result=new charsize;if(pos=strstr(str,oldsubstr)strncpy(result,str,pos-str);*(result+

22、(pos-str)=message;strcat(result,newsubstr);strcat(result,pos+strlen(oldsubstr);cout return result;elsedelete result;return NULL;Ex6.文本统计/*=*Filename:2-6.cpp*Description:Text statistics Function*Version:1.0*Created:05/13/2010 02:37:34 PM*Revision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#i

23、nclude#include using namespace std;struct wc/不使用class是因为这是一个纯数据的对象,虽然它包含一个默认的构造函数。int words;int spaces;int punct;int lines;wc()words=punct=spaces=lines=0;wc wordcount(const char*str);int main()const char*test=By supplying astring class and alsosupporting null-terminated strings,nC+offers arich progr

24、amming environment forstring-intensive tasks.nIts power programming.;coutGiven:nn;cout test endl;wc wcd=wordcount(test);coutnWords:wcd.words endl;coutSpaces:wcd.spaces endl;coutLines:wcd.lines endl;coutPunctuation:wcd.punct endl;return 0;wc wordcount(const char*str)wc data;if(*str)+data.lines;while(

25、*str)if(isalpha(*str)while(isalpha(*str)|*str=)if(*str=)+data.punct;+str;data.words+;elseif(ispunct(*str)+data.punct;else if(isspace(*str)+data.spaces;if(*str=n&*(str+1)+data.lines;+str;return data;Ex7解析一个C型字符串/*=*Filename:2-7.cpp*Description:String Token*Version:1.0*Created:05/14/2010 10:01:58 AM*R

26、evision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#include using namespace std;#define MAX_TOKEN_SIZE 128 const char*gettoken(const char*str);int main()char delims=.,?;!;char str=I like apples,pears,and grapes.Do you?;char*tok;coutObtain the words in asentence.n;tok=strtok(str,deli

27、ms);while(tok)cout tok endl;tok=strtok(NULL,delims);char kvpairs=count=10,name=Tom Jones,jr.,max=100,min=0.01;char kvdelims=,;coutnTokenize key/Value pairs.n;tok=strtok(kvpairs,kvdelims);while(tok)coutKey:tok;if(!strcmp(name,tok)tok=strtok(NULL,);elsetok=strtok(NULL,kvdelims);coutValue:tok endl;tok=

28、strtok(NULL,kvdelims);coutOri String iskvpairs/We want to token the count,12 and the symbol add(+),but we cannot make it via strtok char count=max=12+3/89;count27=19*(min+floor);char countdelims=+;const char*strtok=gettoken(count);while(strtok)cout strtok endl;strtok=gettoken(NULL);coutnn;return 0;c

29、onst char*gettoken(const char*str)static char tokenMAX_TOKEN_SIZE+1;/static makes the return method can be made.static const char*ptr;/static type holds the string last time passed in int count=0;/holds the current character count char*tokptr=token;if(str)ptr=str;while(isspace(*ptr)ptr+;if(isalpha(*

30、ptr)while(isalpha(*ptr)|isdigit(*ptr)*tokptr+=*ptr+;+count;if(count=MAX_TOKEN_SIZE)break;else if(isdigit(*ptr)while(isdigit(*ptr)*tokptr+=*ptr+;+count;if(count=MAX_TOKEN_SIZE)break;else if(ispunct(*ptr)*tokptr+=*ptr+;else return NULL;/Null terminate the token.*tokptr=message;return token;3.String操作实

31、例:Ex8 String基本操作/*=*Filename:2-8.cpp*Description:String Basic Operation*Version:1.0*Created:05/14/2010 02:15:06 PM*Revision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#include using namespace std;int main()/Create some string objects.Three are initialized/using the string literal pa

32、ssed as an argument.string str1(Alpha);string str2(Beta);string str3(Gamma);string str4;/Output astring via cout.coutHere are the original strings:n;coutstr1:str1 endl;coutstr2:str2 endl;coutstr3:str3nn;/Display the maximum string length.coutThe maximum string length is:str1.max_size()nn;/Display th

33、e size of str1.You can use length()instead.这两个方法其实是一个效果,有size只是为了满足兼容STL的要求coutstr1 containsstr1.size()characters.n;/Display the capacity of str1.coutCapacity of str1:str1.capacity()nn;/Display the characters in astring one at atime/by using the indexing operator.for(unsigned i=0;i str1.size();+i)co

34、utstr1:str1iendl;/使用at方法也可以cout endl;/Assign one string to another.str4=str1;coutstr4 after being assigned str1:str4nn;/Concatenate two strings.str4=str1+str3;coutstr4 after begin assigned st1+str3:str4nn;/Insert one string into another.str4.insert(5,str2);coutstr4 after inserting str2:str4nn;/Obtai

35、n asubstring.str4=str4.substr(5,4);coutstr4 after being assigned str4.substr(5,4):str4nn;/Compare two strings.coutCompare strings.n;if(str3 str1)coutstr3 str1n;/使用compare方法能够更加强大的比较String if(str3=str1+str2)coutstr3=str1+str2n;if(str1=str2)coutstr1=str2nn;/Create astring object using another string o

36、bject.coutInitialize str5 with the contents of str1.n;string str5(str1);coutstr5:str5nn;/Erase str4.coutErasing str4.n;str4.erase();/使用clear方法也可以if(str4.empty()coutstr4 is now empty.n;coutSize and capacity of str4 isstr4.size()str4.capacity()nn;/Use push_back()to add characters to str4.for(char ch=A

37、;ch=Z;+ch)str4.push_back(ch);coutstr4 after calls to push_back():str4 endl;coutSize and capacity of str4 is nowstr4.size()str4.capacity()nn;/Set the capacity of str4 to 128.coutSetting the capacity of str4 to 128n;str4.reserve(128);coutCapacity of str4 is now:str4.capacity()nn;/Input astring via cin

38、.coutEnter astring:;cin str1;coutYou entered:str1nn;return 0;Ex9搜索操作/*=*Filename:2-9.cpp*Description:Search String*Version:1.0*Created:05/14/2010 03:16:12 PM*Revision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#include using namespace std;void showresult(string s,string:size_type i)

39、;int main()string:size_type indx;/这是很标准的使用方法,而不是使用int或者unsigned int/Create astring.string str(one two three,one two three);string str2;coutString to be searched:strnn;coutSearching for the first occurrence oftwon;indx=str.find(two);showresult(str,indx);coutSearching for the last occurrence oftwon;in

40、dx=str.rfind(two);showresult(str,indx);coutSearching for the first occurrence of tor hn;indx=str.find_first_of(th);showresult(str,indx);coutSearching for the last occurrence of tor hn;indx=str.find_last_of(th);showresult(str,indx);coutSearching for the first occurrence of any character otherthan o,n

41、,e,or spacen;indx=str.find_first_not_of(one);showresult(str,indx);coutSearching for the last occurrence of any character otherthan o,n,e or spacen;indx=str.find_last_not_of(one);showresult(str,indx);return 0;/Display the results of the search.void showresult(string s,string:size_type i)if(i=string:n

42、pos)/在没有匹配的部分都是返回npos coutNo match found.n;return;coutMatch found at indexi endl;coutRemaining string from point of match:s.substr(i)nn;Ex10.搜索替换操作:这个版本比C型字符串要简单许多,主要原因是String的动态特性和/*=*Filename:2-11.cpp*Description:String Search and Replace*Version:1.0*Created:05/14/2010 03:48:47 PM*Revision:none*Co

43、mpiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#include using namespace std;bool search_and_replace(string&str,const string&oldsubstr,const string&newsubstr);int main()string str=This is atest.So is this.;coutOriginal string:strnn;coutReplacingiswithwas:n;/The following replaces is with was.No

44、tice that/it passes string literals for the substrings./These are automatically converted into string objects.while(search_and_replace(str,is,was)cout str endl;cout endl;/Of course,you can explicitly pass string objects,too.string oldstr(So);string newstr(So too);coutReplaceSowithSo tooendl;search_a

45、nd_replace(str,oldstr,newstr);cout str endl;return 0;bool search_and_replace(string&str,const string&oldsubstr,const string&newsubstr)string:size_type startidx;startidx=str.find(oldsubstr);if(startidx!=string:npos)str.replace(startidx,oldsubstr.size(),newsubstr);return true;return false;Ex11.迭代器的基本使用/*=*Filename:2-13.cpp*Description:String Iterator*Version:1.0*Created:05/14/2010 04:55:41 PM*Revision:none*Compiler:gcc*Author:gnuhpc(*Company:IBM CDL*=*/#include#include#include#include#include using namespace std;int main()string strA(This is atest.);/Create an iter

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 其他


经营许可证编号:宁ICP备18001539号-1