C语言常见字符串函数的实现

本文深入探讨了C语言中常见的字符串操作函数,包括strcpy、strcat、strstr、strcmp和strchr的实现与应用。通过具体实例,展示了如何利用这些函数进行字符串复制、连接、查找子串、比较以及定位特定字符,为读者提供了丰富的代码实践案例。

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

1.实现strcpy

  • 如果两个指针p和n分别指向两个字符串,那么进行p=n运算时这个表达式仅仅是复制了字符串的地址而不是字符串本身,这时为了达到复制字符串本身的效果我们可以使用strcpy()函数。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
	int key;
	int x;
	puts("do you want to re-enter your password\n");
	char password[8] = "abcdefg";
	char password2[10];
	printf("现在的密码是%s\n",password);
	printf("如果需要请输入1不需要输入0\n");
	scanf("%d", &key);
	if (key == 1)
	{
		printf("请输入密码\n");
		scanf("%s",&password2);
		strcpy(password,password2);
		printf("新密码是%s\n", password);
	}
	else
	{
		printf("密码是%s\n", password);
	}
	return 0;
	system ("pause");
}

在这里插入图片描述

2.实现strcat

#define SIZE 80
#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
int main(void)
{
	char name[SIZE];
	char str[] = "'s pen is red";
	puts ("Whose pen is this?");
	gets(name);
	strcat(name, str);
	puts(name);
	puts(str);
	return 0;
}

在这里插入图片描述

3.实现strstr

  • strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。
#include <stdio.h>
#include <string.h>
int main()
{
	char str[] = "this is a simple string";
	char* p;
	p = strstr(str, "simple");
	if (p == NULL)
	{
		printf("不存在\n");
	}
	else
	{
		printf("%s\n", p);
	}
	system("pause");
	return 0;
}

在这里插入图片描述

4. 实现strcmp

#include <stdio.h>
#include <string.h>
#include <cassert>
int Strcmp(const char* str1, const char* str2)
{
	//参数有效性判断
	assert(str1 != NULL && str2 != NULL);
	while (*str1 != '\0' && *str2 != '\0')//确保两个字符串都没有达到结尾,再来进行比较
	{
		if (*str1<*str2)
		{
			return -1;
		}
		else if (*str1 > *str2)
		{
			return 1;
		}
		else
		{
			//往下比较
			++str1;
			++str2;
		}
	}
	//确保循环结束后两字符串至少有一个是到达了\0
	if (*str1 < *str2)//*str1 < *str2,那么str1一定是遇到了\0,str2没有
	{
		return -1;
	}else if (*str1 > * str2)//*str1 >*str2,那么str2一定是遇到了\0,str1没有
	{
		return 1;
	}
	else
	{
		return 0;//两字符串相等
	}
}
int main()
{
	const char* p1 = "hehe";
	const char* p2 = "hehehe";
	int ret = Strcmp(p1,p2);
	if (ret < 0)
	{
		printf("p1<p2\n");
	}
	else if (ret == 0)
	{
		printf("p1=p2\n");
	}
	else
	{
		printf("p1>p2\n");
	}
}

调试结果如下:
在这里插入图片描述

5.实现strchr

  • C 库函数 char *strchr(const char *str, int c) 在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。该函数返回在字符串 str 中第一次出现字符 c 的位置,如果未找到该字符则返回 NULL
#include<stdio.h>
#include<string.h>
int main(void) 
{
	char str1[] = "enahdqihhgfdssas";
	char* p;
	p = strchr(str1,'a');
	while (p != '\0')
	{
		printf("found at %d\n", p - str1 + 1);
		p = strchr(p + 1, 'a');
	}
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值