strcpy,strncpy,strcmp基础功能的实现

实现strcpy的功能(全部复制)

#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])

{
	char arr[30];
	char brr[60];
	printf("请输入两个字符串");
	gets(arr);
	gets(brr);
	for(int i=0;i<30;i++)
	{
		brr[i]=arr[i];	
		
	}
puts(brr);
	return 0;
} 
结果:
ubuntu@ubuntu:q6$ gcc lx1.c
lx1.c: In function ‘main’:
lx1.c:9:2: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
  gets(arr);
  ^~~~
  fgets
/tmp/cc2BIgj3.o:在函数‘main’中:
lx1.c:(.text+0x45): 警告: the `gets' function is dangerous and should not be used.
ubuntu@ubuntu:q6$ ./a.out
请输入两个字符串741852
963852
741852

实现strncpy的功能(给定复制个数)

指定要复制的字符个数, 如果未超出'\0'所对应的长度,那么拼接的就是n的长度。 如果超出'\0'所对应的长度,那么就拼接全部

#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])

{
	char arr[30];
	char brr[60];
	int a,len1=0,len2=0;
	printf("请输入两个字符串");
	gets(arr);
	gets(brr);
	scanf("%d",&a);//输入要复制的位数
	len1=strlen(arr);
	len2=strlen(brr);
	for(int i=0;i<a;i++)
	{
		brr[i]=arr[i];	

	}
	puts(brr);
	return 0;
} 
结果:
ubuntu@ubuntu:q6$ gcc lx1gai3.c 
lx1gai3.c: In function ‘main’:
lx1gai3.c:10:2: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
  gets(arr);
  ^~~~
  fgets
/tmp/ccTX381K.o:在函数‘main’中:
lx1gai3.c:(.text+0x53): 警告: the `gets' function is dangerous and should not be used.
ubuntu@ubuntu:q6$ ./a.out
请输入两个字符串741852
789456123
7
741852

实现strcmp的功能(比较)比较字符串是逐个字符(通过ascii码值)去进行比较,知道遇到不同的字符比较完结束或者遇到'\0'结束

#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])

{
	char arr[30];
	char brr[30];
	int flag;
	printf("请输入两个字符串 ");
	gets(arr);
	gets(brr);
	for(int i=0;arr[i]!='\0'||brr[i]!='\0';i++)
	{
		flag=0;
		if(arr[i]==brr[i])
		{
			flag=1;
				}
		else if(arr[i]>brr[i])
		{
			printf("1\n");
			break;
		}
		else 
		{
			printf("-1\n");
			break;
		}
	}if (flag==1)
	{
	printf("0\n");
	
	return 0;
}
结果:
ubuntu@ubuntu:q6$ gcc lx2.c
lx2.c: In function ‘main’:
lx2.c:10:2: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
  gets(arr);
  ^~~~
  fgets
/tmp/cc6vGRAN.o:在函数‘main’中:
lx2.c:(.text+0x3c): 警告: the `gets' function is dangerous and should not be used.
ubuntu@ubuntu:q6$ ./a.out
请输入两个字符串 741
741
0
ubuntu@ubuntu:q6$ ./a.out
请输入两个字符串 7418
741
1
ubuntu@ubuntu:q6$ ./a.out
请输入两个字符串 741
7418
-1
ubuntu@ubuntu:q6$ ./a.out
请输入两个字符串 782
742
1
ubuntu@ubuntu:q6$ ./a.out
请输入两个字符串 742
782
-1

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值