您的位置:首页 > 其它

strlen,strcpy,strcat,strcmp,strchr 的模拟实现

2017-10-22 19:34 459 查看
c语言中对于字符串的处理是非常不方便的。因为C语言中字符串本质上是一个字符数组,一个常量指针。

模拟实现一下字符串的这些常用函数,加深对数组及常量指针的理解:

//
// Created by cat on 2017/10/22.
//

#include <stdio.h>

/*
对字符串函数的模拟实现
*/
int strlen(const char *__s);
int strcmp(const char *__s1, const char *__s2);
char *strcat(char *dst, const char *src);
char *strcpy(char *dst, const char *src);
char *strchr(const char *__s, int __c);
char *strstr(const char *__big, const char *__little);

int main(int argc, char const *argv[])
{

printf("strlen(Hello) = %d\n", strlen("Hello"));
printf("strcmp(abc,abc) = %d\n", strcmp("abc", "abc"));

char a[15] = "hello";
char b[] = "world";

printf("strcat = %s\n",strcat(a,b) );

char c[] = "Hello";
char d[] = "world";
printf("strcpy = %s\n", strcpy(c,d));

char s[] = "python,hello";
char p = 't';

printf("strchr = %s\n", strchr(s,p));
return 0;
}

char *strstr(const char *__big, const char *__little){

// todo
return NULL;
}

char *strchr(const char *s1, int c){

int i=0;
while(1){
// printf("s1 = %c\n", *(s1+i));
if (*(s1+i)==c ){
return (char *)(s1+i); // 这里必须强制转换一下,否则运行失败
}
if(*(s1+i)=='\0'){
break;
}
i +=1;
}
return NULL;

}

char *strcpy(char *s1, const char *s2){
int i=0;
while(1){
char t  = s2[i];
if('\0' == t){
break;
}
s1[i] = s2[i];
i++;
}

return s1;

}

char *strcat(char *s1, const char *s2){
int s1len = strlen(s1);
int i=0;
while(1){
char t  = s2[i];
if('\0' == t){
break;
}
s1[s1len + i] = s2[i];
i++;
}

return s1;

}

int strcmp(const char *s1, const char *s2){
int totals1 = 0;
int i=0;
while(1){
char t  = s1[i];
if('\0' == t){
break;
}
totals1 += (int)t;
i++;
}

int totals2 = 0;
i = 0;
while(1){
char t = s2[i];
if('\0' == t){
break;
}
totals2 += (int)t;
i++;
}

return totals1 - totals2;

}

int strlen(const char *str){
int len = 0;
int i = 0;

while(1){
char t = str[i];
if( '\0'==t ){
break;
}
// printf("t = %c ", t );
i++;
len  = i;
}

return len;
}

/*
console:
strlen(Hello) = 5
strcmp(abc,abc) = 0
strcat = helloworld
strcpy = world
strchr = thon,hello
[Finished in 0.4s]
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐