c语言字符串函数使用.docx
文本预览下载声明
Strcpy:拷贝一个字符串到另一个字符串,char *strcpy(char *destin,char *source)。Strcat:字符串拼接函数,cat是catanat的缩写,char *strchr(char *destin,char *source).将source字符串拼接到destin之后,结果返回destin的指针。例:#include stdio.h#include string.h#include stdlib.hvoid main(){char *destination=(char *)malloc(sizeof(char)*25);char *blank= ;char *c=c++;char *Borland=Borland;strcpy(destination,Borland);strcat(destination,blank);strcat(destination,c);puts(destination);}Strchr:在一个串中查找给定字符的第一个匹配指出,char *strchr(char *str,charstr).返回的是给定字符串的第一个等于给定字符的指针,如果用puts打印返回字符指针,会打印出之后的字符串,例:#include stdio.h#include string.hvoid main(){char string[15];char *ptr,c=r;strcpy(string,this is a string);ptr=strchr(string,c);if(ptr)printf(the character %c is at position:%d\n,c,ptr-string);elseprintf(error\n);}Strcmp:串比较函数,intstrcmp(char *str1,char *str2),根据asc码比较大小,若str1大,则返回大于0的值,相等,为零,小于,则返回小于零的值。对于大写也成立,小写字母要大于相同字母的大写。例:#include string.h#include stdio.hvoid main(){char *buf1=bbB, *buf2=bbb;intptr;ptr=strcmp(buf1,buf2);if(ptr0){printf(%s大于%s\n,buf1,buf2);}else if(ptr==0){printf(%s等于%s\n,buf1,buf2);}else {printf(%s小于%s\n,buf1,buf2);}}Strncmp与strnicmp:两个都是比较字符串的前n个的大小,区别在于strncmp区分大小写,而strnicmp不区分大小写,intstrncmp(char *str1,char *str2,int maxlen);intstrnicmp(char *str1,char *str2,int maxlen)。返回值同strcmp。Strspn和strcspn:intstrcspn(char *s,char *reject),strcspn()从参数s字符串的开头计算连续的字符,而这些字符都完全不在参数reject所指的字符串当中,即若strcspn返回的值为n,则代表字符串s开头连续有n个字符都不含字符串reject内的字符。其返回值为前面不相同字符串的长度,strcspn=string+counter+span。例:*str=”Linux was first developed for 386/486-based pcs.”;Strcspn(str,””)的返回值为5,因为只空格前不同的字符是Linux,长度为5。Strcspn(str,”/-”)的返回值为33,因为计算出现/或-前的字符串长度,即6之前的长度。Strcspn(str,”0123456789”)的返回值为30,因为出现数字前的字符串长度为30。Intstrspn(char *s,char *accept);strspn()从参数s字符串的开头计算连续的字符,而这些字符完全都是accept所指字符串中的字符,简单的说,strspn()返回的数值为n,则代表字符串s开头连续有n个字符都死属于字符串accept内的字符。例:*str=”Linux was first developed for 386/486-based pcs.”;Strspn(str,”Linux”)的返回值为5,因为str的前5个字符都属于Linux字符串中的字符。Strspn(str,”-”)的返回值为0。Strcspn(str,”0123456789”)的返回值为0.Strdup:char *strdup(char *s),将字符串s复制到自动动态分配的内存当
显示全部