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

上传人:b****6 文档编号:4106237 上传时间:2022-11-27 格式:DOCX 页数:8 大小:22.64KB
下载 相关 举报
用思维导图和实例学习C之一字符串处理.docx_第1页
第1页 / 共8页
用思维导图和实例学习C之一字符串处理.docx_第2页
第2页 / 共8页
用思维导图和实例学习C之一字符串处理.docx_第3页
第3页 / 共8页
用思维导图和实例学习C之一字符串处理.docx_第4页
第4页 / 共8页
用思维导图和实例学习C之一字符串处理.docx_第5页
第5页 / 共8页
点击查看更多>>
下载资源
资源描述

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

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

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

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

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

1.本章思维导图:

Example1:

char*strcpy(char*target,constchar*source){char*t=target;//Copythecontentsofsourceintotarget.while(*source)*target++=*source++;//Null-terminatethetarget.*target='[message]';//Returnpointertothestartoftarget.returnt;}

Example2:

void*memmove(void*target,constvoid*source,size_tcount)这个函数即使是在源和目的字符串有所重叠时操作也能成功,虽然source为const,但是其指向的array也可能被修改。

2.C型字符串操作实例:

Ex1.基本操作

/**===**Filename:

2-1.cpp**Description:

FundamentalOperationsinCTypeString**Version:

1.0*Created:

05/11/201010:

43:

11AM*Revision:

none*Compiler:

gcc**Author:

gnuhpc(warmbupt@*Company:

IBMCDL**===*/#include#includeusingnamespacestd;

intmain(intargc,char*argv){charstrA[7]="UP";charstrB[5]="DOWN";charstrC[5]="LEFT";charstrD[6]="RIGHT";

/*Display*/cout"Herearethestrings:

"endl;cout"strA:

"strAendl;cout"strB:

"strBendl;cout"strC:

"strCendl;cout"strD:

"strD"\n\n";

//DisplaythelengthofstrA.cout"LengthofstrAis"strlen(strA)endl;cout"SizeofstrAis"sizeof(strA)endl;//ConcatenatestrBwithstrAcout"TheresultofConcatenateisstrA:

"

//CopystrCintostrB,andpartiallystrDintostrAcout"TheresultofCopyis:

"cout"TheresultofpartiallyCopyisstrA:

"

//ComparestrCwithstrBif(!

strcmp(strC,strB)){cout"strCisequaltostrB!

"}

if(!

strncmp(strD,strA,3)){cout"strDisequaltostrApartially!

"}

return0;

}

Ex2.搜索匹配相关操作

/**===**Filename:

2-2.cpp**Description:

SearchOperationinCtypeString**Version:

1.0*Created:

05/11/201011:

38:

15AM*Revision:

none*Compiler:

gcc**Author:

gnuhpc(warmbupt@*Company:

IBMCDL**===*/

#include#includeusingnamespacestd;intmain(void){constchar*url="HerbS";constchar*url2="Apache.org";constchar*emailaddr="Herb@HerbS";constchar*tld={".com",".net",".org"};constchar*p;//First,determineifurlandurl2,.net,or.org.for(inti=0;i3;i++){p=strstr(url,tld[i]);if(p)couturl"hastop-leveldomain"tld[i]endl;p=strstr(url2,tld[i]);if(p)couturl2"hastop-leveldomain"tld[i]endl;}//Searchforaspecificcharacter.p=strchr(emailaddr,'@');if(p)cout"Sitenameofe-mailaddressis:

"p+1endl;//Searchforanyofasetofcharacters.Inthiscase,//findthefirst@orperiod.p=strpbrk(emailaddr,"@.");if(p)cout"Found"*pendl;

//Searchforthebeginningif(strspn(url2,"Apache")==6){cout"Url2beginswiththe\"Apache\""endl;}

//与strchr正好倒过来if(p=strrchr(emailaddr,'b')){coutpendl;}return0;}

Ex3.倒置一个字符串

我们用了四种方法,最后一种方法经常在面试笔试题中出现。

/**===**Filename:

2-3.cpp**Description:

Reverseastring**Version:

1.0*Created:

05/12/201003:

08:

09PM*Revision:

none*Compiler:

gcc**Author:

gnuhpc(warmbupt@*Company:

IBMCDL**===*/#include#includeusingnamespacestd;voidrevstr(char*str);voidrevstr_p(char*str);voidrevstr_recursive(char*str,intstart,intend);char*(revstrcpy)(char*rstr,constchar*orgstr);intmain(){charstr="abcdefghijklmnopqrstuvwxyz";char*des=newchar[27];cout"Originalstring:

"strendl;revstr(str);cout"Reversedstring:

"strendl;revstr_p(str);cout"Reversedstringusingpointer:

"strendl;revstr_recursive(str,0,strlen(str)-1);cout"Reversedstringusingrecursive:

"strendl;cout"Reversedstringusingcopymethod:

"revstrcpy(des,str)endl;return0;}

voidrevstr(char*str){inti,j;chart;for(i=0,j=strlen(str)-1;ij;++i,--j){t=str[i];str[i]=str[j];str[j]=t;}}

//Reverseastringinplace.Usepointersratherthanarrayindexing.voidrevstr_p(char*str){chart;char*inc_p=str;char*dec_p=&str[strlen(str)-1];while(inc_p=dec_p){t=*inc_p;*inc_p++=*dec_p;*dec_p--=t;}}

voidrevstr_recursive(char*str,intstart,intend){if(startend)revstr_recursive(str,start+1,end-1);elsereturn;chart=str[start];str[start]=str[end];str[end]=t;}

char*(revstrcpy)(char*rstr,constchar*orgstr){//返回rstr的原始值使函数能够支持链式表达式,增加了函数的"附加值"。

同样功能的函数,如果能合理地提高的可用性,自然就更加理想。

if((rstr==NULL)||(orgstr==NULL))throw"Invalidargument(s)";

char*dst=rstr;dst+=strlen(orgstr);*dst--='[message]';while(*orgstr)*dst--=*orgstr++;returnrstr;}

Ex4.忽略大小写的字符串比较

/**===**Filename:

2-4.cpp**Description:

IgnoretheLettercasewhencompared**Version:

1.0*Created:

05/12/201003:

44:

34PM*Revision:

none*Compiler:

gcc**Author:

gnuhpc(warmbupt@*Company:

IBMCDL**===*/

#include#includeusingnamespacestd;intstrcmp_ign_case(constchar*str1,constchar*str2);intmain(void){charstrA="tesT";charstrB="Test";charstrC="testing";charstrD="Tea";intresult;cout"Herearethestrings:

"endl;cout"strA:

"strAendl;cout"strB:

"strBendl;cout"strC:

"strCendl;cout"strD:

"strD"\n\n";//Comparestringsignoringcase.result=strcmp_ign_case(strA,strB);result=strcmp_ign_case(strA,strC);result=strcmp_ign_case(strA,strD);result=strcmp_ign_case(strD,strA);return0;}//Asimplestringcomparisonfunctionthatignorescasedifferences.intstrcmp_ign_case(constchar*str1,constchar*str2){constchar*str1_cp=str1;constchar*str2_cp=str2;while(*str1_cp&&*str2_cp){if(tolower(*str1_cp++)!

=tolower(*str2_cp++))break;}intresult=tolower(*str1_cp)-tolower(*str2_cp);coutstr1"is";if(!

result)cout"equalto";elseif(result0)cout"lessthan";elsecout"greaterthan";coutstr2endl;returnresult;}

Ex5.搜索替换

/**===**Filename:

2-5.cpp**Description:

Replacethesub_strwithanotherstr**Version:

1.0*Created:

05/12/201004:

07:

02PM*Revision:

none*Compiler:

gcc**Author:

gnuhpc(warmbupt@*Company:

IBMCDL**===*/

#include#include#includeusingnamespacestd;boolsearch_and_replace(char*orgstr,intmaxlen,constchar*oldsubstr,constchar*newsubstr);char*search_and_replace_alloc(constchar*str,constchar*oldsubstr,constchar*newsubstr)throw(bad_alloc);intmain(void){charstr[80]="alphabetagammaalphabetagamma";char*ptr=NULL;cout"Originalstring:

"str"\n\n";cout"First,replaceallinstancesofalphawithepsilon.\n";//Replacealloccurrencesofalphawithepsilon.while(search_and_replace(str,sizeof(str),"alpha","epsilon"))cout"Afterareplacement:

"strendl;cout"Second,replaceoneinstancesofepsilonwithalpha.\n";

try{ptr=search_and_replace_alloc(str,"epsilon","alpha");}catch(bad_allocexc){//Takeappropriateactionhere.}if(ptr){cout"Afterareplacement:

"ptrendl;deleteptr;}

return0;}boolsearch_and_replace(char*orgstr,intmaxlen,constchar*oldsubstr,constchar*newsubstr){char*pos=NULL;if((orgstr==NULL)||(oldsubstr==NULL)||(newsubstr==NULL))returnfalse;intlen=strlen(orgstr)-strlen(oldsubstr)+strlen(newsubstr);if(lenmaxlen)returnfalse;if(pos=strstr(orgstr,oldsubstr)){memmove(pos+strlen(newsubstr),pos+strlen(oldsubstr),strlen(pos)-strlen(oldsubstr)+1);strncpy(pos,newsubstr,strlen(newsubstr));returntrue;}else{returnfalse;}}

char*search_and_replace_alloc(constchar*str,constchar*oldsubstr,constchar*newsubstr)throw(bad_alloc){constchar*pos=NULL;if((str==NULL)||(oldsubstr==NULL)||(newsubstr==NULL))returnNULL;intsize=strlen(str)+strlen(newsubstr)-strlen(oldsubstr)+1;char*result=newchar[size];if(pos=strstr(str,oldsubstr)){strncpy(result,str,pos-str);*(result+(pos-str))='[message]';strcat(result,newsubstr);strcat(result,pos+strlen(oldsubstr));coutreturnresult;}else{deleteresult;returnNULL;}}

Ex6.文本统计

/**===**Filename:

2-6.cpp**Description:

TextstatisticsFunction**Version:

1.0*Created:

05/13/201002:

37:

34PM*Revision:

none*Compiler:

gcc**Author:

gnuhpc(warmbupt@*Company:

IBMCDL**===*/

#include#includeusingnamespacestd;structwc{//不使用class是因为这是一个纯数据的对象,虽然它包含一个默认的构造函数。

intwords;intspaces;intpunct;intlines;wc(){words=punct=spaces=lines=0;}};wcwordcount(constchar*str);intmain(){constchar*test="Bysupplyingastringclassandalso""supportingnull-terminatedstrings,\nC++""offersarichprogrammingenvironmentfor""string-intensivetasks.\nIt'spowerprogramming.";cout"Given:

""\n\n";couttestendl;wcwcd=wordcount(test);cout"\nWords:

"wcd.wordsendl;cout"Spaces:

"wcd.spacesendl;cout"Lines:

"wcd.linesendl;cout"Punctuation:

"wcd.punctendl;return0;}wcwordcount(constchar*str){wcdata;if(*str)++data.lines;while(*str){if(isalpha(*str)){while(isalpha(*str)||*str=='\''){if(*str=='\'')++data.punct;++str;}data.words++;}else{if(ispunct(*str))++data.punct;elseif(isspace(*str)){++data.spaces;if(*str=='\n'&&*(str+1))++data.lines;}++str;}}returndata;}

Ex7解析一个C型字符串

/**===**Filename:

2-7.cpp**Description:

StringToken**Version:

1.0*Created:

05/14/201010:

01:

58AM*Revision:

none*Compiler:

gcc**Author:

gnuhpc(warmbupt@*Company:

IBMCDL**===*/

#include#includeusingnamespacestd;

#defineMAX_TOKEN_SIZE128constchar*gettoken(constchar*str);intmain(){chardelims=".,?

;!

";charstr="Ilikeapples,pears,andgrapes.Doyou?

";char*tok;cout"Obtainthewordsinasentence.\n";tok=strtok(str,delims);while(tok){couttokendl;tok=strtok(NULL,delims);}charkvpairs="count=10,name=\"TomJones,jr.\",max=100,min=0.01";charkvdelims="=,";cout"\nTokenizekey/Valuepairs.\n";tok=strtok(kvpairs,kvdelims);while(tok){cout"Key:

"tok"";if(!

strcmp("name",tok)){tok=strtok(NULL,"\"");}else{tok=strtok(NULL,kvdelims);}cout"Value:

"tokendl;tok=strtok(NULL,kvdelims);}

cout"OriStringis"kvpairs

//Wewanttotokenthecount,12andthesymboladd(+),butwecannotmakeitviastrtokcharcount="max=12+3/89;count27=19*(min+floor);";charcountdelims="=+";

constchar*strtok=gettoken(count);while(strtok){coutstrtokendl;strtok=gettoken(NULL);}cout"\n\n";return0;}

constchar*gettoken(constchar*str){staticchartoken[MAX_TOKEN_SIZE+1];//staticmakesthereturnmethodcanbemade.staticconstchar*ptr;//statictypeholdsthestringlasttimepassedinintcount=0;//holdsthecurrentcharactercountchar*tokptr=token;if(str){ptr=str;}while(isspace(*ptr))ptr++;if(isalpha(*ptr)){while(isalpha(*ptr)||isdigit(*ptr)){*tokptr++=*ptr++;++count;if(count==MAX_TOKEN_SIZE)break;}}elseif(isdigit(*ptr)){while(isdigit(*ptr)){*tokptr++=*ptr++;++count;if(count==MAX_TOKEN_SIZE)break;}}elseif(ispunct(*ptr)){*tokptr++=*ptr++;}elsereturnNULL;//Nullterminatethetoken.*tokptr='[message]';returntoken;}

3.String操作实例:

Ex8String基本操作

/**===**Filename:

2-8.cpp**Description:

StringBasicOperation**Version:

1.0*Created:

05/14/201002:

15:

06PM*Revision:

none*Compiler:

gcc**Author:

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

当前位置:首页 > 初中教育 > 政史地

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1