C语言实现strcpy、strncpy、strcmp、strncmp的功能

本文介绍了C语言中四个重要的字符串处理函数:strcpy用于复制字符串,strncpy允许指定复制的字符数,strcmp比较两个字符串是否相等,strncmp则在指定长度内比较两个字符串。通过示例展示了它们的使用方法和返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

strcpy

#include <stdio.h>
void main()
{
	char a[50],b[20];
	int i=0;
	printf("str1=");
	gets(a);
	printf("str2=");
	gets(b);
	while(a[i]!='\0')
	{
		a[i]='\0';
		i++;
	}
	i=0;
	while(b[i]!='\0')
	{
		a[i]=b[i];
		i++;
	}
	a[i]='\0';
	printf("str1=");
	printf("%s\n",a);
}

结果:
str1=lkjiuy
str2=aaaa
str1=aaaa

strncpy

#include <stdio.h>
void main()
{
	char a[50],b[20];
	int i=0,n;
	printf("str1=");
	gets(a);
	printf("str2=");
	gets(b);
	printf("n=");
	scanf("%d",&n);
	while(i<n)
	{
		a[i]=b[i];
		i++;
	}
	printf("str1=");
	printf("%s\n",a);
}

结果:
str1=jjjjj
str2=aaaaa
n=2
str1=aajjj

strcmp

#include <stdio.h>
void main()
{
	char a[50],b[20];
	int i=0,n=0;
	printf("str1=");
	gets(a);
	printf("str2=");
	gets(b);
	while(a[i]!='\0')
	{
		if(a[i]!=b[i])
			break;
		i++;
	}
	if(a[i]>b[i])   n=1;
	else if (a[i]<b[i])   n=-1;
	else n=0;
	printf("返回值:%d\n",n);
}

结果:
str1=abcdffz
str2=abcddfz
返回值:1

strncmp

#include <stdio.h>
void main()
{
	char a[50],b[20];
	int i=0,n,m=0;
	printf("str1=");
	gets(a);
	printf("str2=");
	gets(b);
	printf("n=");
	scanf("%d",&n);
	while(i<n-1)
	{		
		if(a[i]!=b[i])
			break;
		i++;
	}
	
	if(a[i]>b[i])   m=1;
	else if (a[i]<b[i])   m=-1;
	else m=0;
	printf("返回值=%d\n",m);
}

str1=abcddd
str2=abdcc
n=3
返回值=-1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值