假期作业2.12

用指针实现strlen、strcpy、strcat、strcmp

#include 
#include 
int mystrlen(char *s)
{
	char *p = s;
	int n=0;
	while(*p++ !='\0')
	{
		n++;
	}
	return n;
}
int mystrcmp(char *p,char *q)
{
	for(;*p == *q;q++,p++)
	{		
		if('\0' == *p)
			return 0;
	}
	return *p - *q;
}
char * mystrcpy(char *dest,char *src)
{
	char *d = dest;
	while(*d++ = *src++);
	return dest;
}
char *mystrcat(char *dest,char *src)
{
	strcpy(dest+mystrlen(dest),src);
	return dest;
}
int main(int argc, const char *argv[])
{
	char a[100];
	char b[100];
	gets(a);
	gets(b);
	char c[100];
	printf("alen=%d\n",mystrlen(a));
	printf("blen=%d\n",mystrlen(b));
	printf("%d\n",mystrcmp(a,b));

	mystrcpy(c,a);
	puts(c);
	mystrcat(a,b);
	puts(a);

	return 0;
}

写一个swap函数实现两数交换

#include 
#include 
void swap(int *p1,int *p2)
{
	int tmp;
	tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
int main(int argc, const char *argv[])
{
	int a = 0;
	int b = 0;
	scanf("%d %d",&a,&b);
	int *p=&a;
	int *q=&b;
	printf("交换前:%d,%d\n",a,b);
	swap(p,q);
	printf("交换后:%d,%d\n",*p,*q);
	return 0;
}

你可能感兴趣的:(c语言)