一些字符串函数的实现
http://www.cnblogs.com/JCSU/articles/1305401.html【参考】
这些函数实现最好参考linux内核源码,向大师学习!
#include <stdio.h> #include <stdlib.h> #include <string.h> static char *str_cpy(char *dest, const char *src) { int i = 0; while(*dest++ = *src++); return dest; } char str_rev(char *s) { char *d = s + strlen(s) - 1; char temp; while(d > s) { temp = *d; *d = *s; *s = temp; d--; s++; } } static int str_len(const char *s) { int len = 0; while(*s++) len++; return len; }
static char *str_cat(char *dest, const char *src) { char *const old = dest; while(*dest) dest++; while(*dest++ = *src++); return old; } /*static int str_cmp(const char *dst, const char *src) { int i = 0; while(*(dst + i) == *(src + i)) { if(*(src+i) == '\0') return 0; i++; } if(*dst > *src) return 1; else return -1; }*/ int str_cmp(const char * cs, const char * ct) { signed char __res; while(1) { if((__res = *cs - *ct++) != 0 || !cs++) break; } return __res; }
int main(void) { char a[20]="hello"; char b[10]; char c[]="hellz";
str_cpy(b,a); printf("str_cpy:b<-a:%s \n", b);
str_rev(a); printf("str_rev:a=%s \n", a);
printf("str_cmp:%d \n",str_cmp(a, c));
str_len(b); printf("str_len:b=%d \n", str_len(b)); printf("strcat:a+b:%s \n", str_cat(a,c));
return 0; }
|
一个简单的回文字符串检测
#include <stdio.h> #include <string.h>
static int str_hui(const char *src);
void main(void) {
char src[]="abcdcba";
printf("%s %s\n", src, str_hui(src) ? "no" : "yes"); printf("%s\n", src); }
static int str_hui(const char *src) { const char *end = src;//*end = src + strlen(src) - 1;定位结尾效果相同 while(*end != '\0') ++end; --end; while(end >= src) { if(*src++ != *end--) { return 1; } } return 0; }
|
注意:1,如何定位到文件尾部 2,返回输出的技巧
阅读(1170) | 评论(0) | 转发(0) |