C:字符串操作
版权声明:原创作品,如需转载,请与作者联系。否则将追究法律责任。 |
1.字符串连接 /*append string t to the end of string s*/ void strapd(char *s,char *t) { while(*s) s++; while(*t) *s++=*t++; *s='\0'; } 2.字符串长度 /*return the length of string s*/ int strlen(const char *s) { const char *cptr=s; while(*s) s++; return s-cptr; } 3.字符串判等 #define TRUE 1 #define FALSE 0 /*return 1 for equals between string s and strng t*/ /*return 0 for not equals */ int streql(const char *s,const char *t) { while(*s==*t && *s && *t){ s++; t++; } if(!*s && !*t) return TRUE; else return FALSE; } 4.字符串尾匹配 #define TRUE 1 #define FALSE 0 /*if found string t at the end of string s,return 1*/ /*else return 0*/ int strend(char *s,char *t) { char *bs=s; /*begining of s*/ char *bt=t; /*begining of t*/ while(*s) /*end of s*/ s++; while(*t) /*end of t*/ t++; for(;*s==*t;s--,t--) if(t==bt||s==bs) break; /*reach the begining*/ if(*s==*t && t==bt && *s) return TRUE; return FALSE; } 5.将匹配的单个字符从源字符串中删除 /*remove all char c from string s*/ void charrm(char *s, int c) { char *tar; tar=s; for(;*s;s++) if(*s !=c) *tar++=*s; *tar='\0'; } 6.将匹配的字符串从源字符串中删除 /*remove all string c from string s*/ void strrm(char *s,char *c) { char *tar; char *bms; /*beginning position for matching*/ char *bc; /*begining of c*/ tar=s; for(;*s;s++){ if(*s !=*c) *tar++=*s; else{ bms=s; bc=c; /*begin macthing*/ for(;*bc && *s && *s==*bc;s++,bc++) ; if(!*bc) /*matched*/ s--;/*for the last s++ in loop for above*/ else if(!*s) {/*unmatched and will never be matched*/ for(;*bms;bms++) *tar++=*bms; *tar='\0'; return; } else/*unmatched*/ s=bms; } } *tar='\0'; } 7.扩展字符串 将类似于a-z之类的速记符号扩展为abc...xyz(26个字母).扩展的依据是字符在ASCII中的顺序. /*expand shortand notation in string s into string t*/ /*a-e:abcde*/ void strepd(char *s,char *t) { char c; while((c=*s++)!='\0') if(*s =='-' && *++s >=c){ while(c<*s) /*expand*/ *t++=c++; }else *t++=c; *t='\0'; } 8.返回首个匹配字符串的位置 /*return the leftest position of string t in string s */ int strlidx(char *s,char *t) { char *bs; /*begining of s*/ char *bms; /*begining position for matching*/ char *bt; /*begining of t*/ bs=s; for(;*s;s++) if(*s==*t){ bms=s; bt=t; for(;*bt && *s && *s==*bt;bt++,s++) ; if(!*bt) /*matched*/ return bms-bs; else if (!*s)/*unmatched and will never be matched*/ return -1; else /*unmatched*/ s=bms; } return -1; } 9.返回末个匹配字符串的位置 /*return the rightest position of t in s */ int strridx(char *s,char *t) { char *es; /*end of s*/ char *et; /*end of t*/ char *emt; /*end position for matching in t*/ char *ems; /*end position for matching in s*/ es=s; while(*es) /*end of s*/ es++; es--; /*exclude '\0'*/ et=t; while(*et) /*end of t*/ et++; et--; /*exclude '\0'*/ for(;es!=s;es--) if(*es==*et){ emt=et; ems=es; for(;*es==*emt;es--,emt--){ if(emt==t||es==s) break; } if(*es==*emt && emt==t && *es)/*matched*/ return es-s; else if(es==s)/*unmatched and will never be matched*/ return -1; else /*unmatched*/ es=ems; } return -1; } 本文出自 “子 孑” 博客,转载请与作者联系! 本文出自 51CTO.COM技术博客 |



zhangjunhd
博客统计信息
热门文章
最新评论
友情链接

