0
点赞
收藏
分享

微信扫一扫

【C语言】常用字符串操作函数及其模拟实现

字符串操作函数的头文件为string.h

1.strlen

计算字符串长度

strlen在识别到\0后停止,如果字符串末尾没有/0它会继续读取下去直到读取到一个\0

#include <stdio.h>
#include <string.h>
int main()
{
char* a = "hello code";//空格也是一个字符
printf("%d", strlen(a));
return 0;
}

【C语言】常用字符串操作函数及其模拟实现_i++

 my_strlen

/0也是0当*test到达末尾/0时结束返回统计到的字符数量

#include <stdio.h>
#include <string.h>
#include <assert.h>
int my_strlen(const char* test)
{
assert(test);
int i = 0;
while (*test++)
{
i++;
}
return i;
}
int main()
{
char* a = "hello code";
printf("%d\n", my_strlen(a));
return 0;
}

2.strcpy

将一个字符串拷贝到另一个字符串之中

#include <stdio.h>
#include <string.h>
int main()
{
char* ch = "hello code";
char cb[20] = "##################";
strcpy(cb, ch);
printf("%s\n", ch);
printf("%s\n", cb);
return 0;
}

【C语言】常用字符串操作函数及其模拟实现_#include_02

【C语言】常用字符串操作函数及其模拟实现_字符串_03

my_strcpy

char* my_strcpy(char* destination, const char* source)
{
assert(destination&&source);
int i = 0;
while (*(destination+i)=*(source+i))
{
i++;
}
return destination;
}
int main()
{
char* ch = "hello code";
char cb[20] = "##################";
my_strcpy(cb, ch);
printf("%s\n", ch);
printf("%s\n", cb);
return 0;
}

3.strcat

将一个字符串追加到另一个字符串末尾

#include <stdio.h>
#include <string.h>
#include <assert.h>
char* my_strcat(char* destination,const char* source)
{
assert(destination&&source);
int i = 0;
while (*(destination+i))
{
i++;
}
int j = 0;
while (*(destination+i) = *(source+j))
{
j++;
i++;
}
return destination;
}
int main()
{
char arr[20] = "hello ";
char* ch = "code";
my_strcat(arr, ch);
printf("%s", arr);
return 0;
}

4.strcmp

int strcmp( const char *string1, const char *string2 );

将两个字符串进行比较如果完全一样返回0,如果不一样比较第一个不同的元素,左边>右边返回正值,右边>左边返回负值

int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2);
int i = 0;
while (*(str1+i) == *(str2+i))
{
if (*(str1 + i) == '\0')
{
return 0;
}
i++;
}
return *(str1+i) - *(str2+i);
}


5.strstr

strstr可以判断一个字符串是否是另一个字符串的子串

简单来说就是

char* str1="abcdefg";
char* str2="cd";

【C语言】常用字符串操作函数及其模拟实现_字符串_04

str2可以在str1中找到str2就是str1的子串

char *strstr( const char *string, const char *strCharSet );

 如果找到则返回母串上对应元素的地址,比如

strstr(str1,str2);

【C语言】常用字符串操作函数及其模拟实现_字符串_05

返回的就是str1中c的地址

如果未找到返回空指针

暴力求解

char* my_strstr(const char* str1, char* str2)
{
char* cp = (char*)str1;
char* s1, * s2;
if (!*str2)
return((char*)str1);
while (*cp)
{
s1 = cp;
s2 = (char*)str2;
while (*s1 && *s2 && !(*s1 - *s2))
s1++, s2++;
if (!*s2)
return(cp);
cp++;
}
return(NULL);
}

如果需要更加优秀的解决方法可以了解一下KMP算法


举报

相关推荐

0 条评论