1.实现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
#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;
}