今天将一周所学的C基础从头梳理了一般,并完成了作业:
-
strlen
:
#include<stdio.h>
#include<string.h>
int mylen(char *p){
// char *pa = p;
int len = 0;
while(*p != '\0'){
len++;
p++;
}
return len-1;
}
int main(){
char arr[32] = {'\0'};
printf("input string:");
fgets(arr,32,stdin);
int str_len = mylen(arr);
printf("str_len = %d\n",str_len);
//printf("strlen(arr) = %d\n",(int)strlen(arr));
return 0;
}
-
strcpy
:
#include<stdio.h>
#include<string.h>
char* mycpy(char *p1,char *p2){
return p2;
}
int main(int argc,char *argv[]){
char arr[32] = {'\0'};
char buf[32] = {'\0'};
printf("input first string:");
fgets(arr,32,stdin);
printf("input second string:");
fgets(buf,32,stdin);
printf("%s\n",mycpy(arr,buf));
printf("%s\n",strcpy(arr,buf));
return 0;
}
-
strcmp
:
#include<stdio.h>
#include<string.h>
/******************自制实现比较字符串的功能******************/
int mycmp(char *p1,char *p2){
int count=0;
int return_i;
while(*p1 == *p2){ //判断字符串是否相等
p1++;
p2++;
if(*p1==10 && *p2==10) {
count++;
break;
}
}
if(count==1)
return 0;
else{
return_i=*p1-*p2; //不相等时,判断返回值
if(*p1==10 || *p2==10)
return_i = *p1-*p2;
return return_i;
}
}
int main(int argc,char *argv[]){
char arr[32] = {'\0'};
char buf[32] = {'\0'};
printf("input first array:");
fgets(arr,32,stdin);
printf("input second array:");
fgets(buf,32,stdin);
int i = mycmp(arr,buf); //主函数进行调用
printf("%d\n",i);
printf("%d\n",strcmp(arr,buf));
return 0;
}
-
strcat
:
#include<stdio.h>
#include<string.h>
char *mycat(char *p1,char *p2){
char arr_p[32] = {0};
char *p = arr_p;
while(*p1 != '\0'){
*p = *p1;
p1++;
p++;
}
while(*p2 != '\0'){
*p = *p2;
p2++;
p++;
}
return arr_p;
}
int main(int argc,char argv[]){
char arr[32] = {'\0'};
char buf[32] = {'\0'};
printf("input frist string:\n");
fgets(arr,32,stdin);
printf("input srcond string:\n");
fgets(buf,32,stdin);
printf("%s\n",mycat(arr,buf));
// printf("%s\n",strcat(arr,buf));
}
网友评论