一.strcat与strncat;字符拼接函数
strcat与strncat函数的格式:
char *strcat(char *dest, const char *src);
char *strncat(char *dest, const char *src, size_t n);
对strcat函数进行封装:
void strcat_s(char *dest,char *src)
{
int i = 0;
int n = strlen(dest);//计算DEST的长度
while(src[i]!='\0')
{
dest[n+i] = src[i];
i++;
}
}
对sncat函数进行封装:
void strncat_s(char *dest,char *src,int length)
{
int i = 0;
int n = strlen(dest);
while(i<n)
{
dest[length +i] = src[i];
i++;
}
}
代码展示:
#include<stdio.h>
#include<string.h>
int main()
{
char s1[20] = "happy ";
char s2[] = "new year";
char s3[30] = "\0";
strcat(s1, s2);
printf("%s\n", s1);
strncat(s3, s1, 3);
printf("%s\n", s3);
return 0;
}
输出打印为:“happy new year”
? ? ? ? ? ? "hap"
二.strcmp与strncmp;字符比较函数
strcmp与strncmp函数的格式:
int strcmp(const char *str1, const char *str2); int strncmp(const char *str1, const char *str2, size_t n);
对strcmp函数进行封装:
int strcmp_s(char *dest,char *src)
{
int i = 0;
int n;
int n1 = strlen(dest);
int n2 = strlen(src);
if(n1>n2)
{
n = n2;
}
else
{
n = n1;
}
while(i<=n)
{
if(dest[i]>src[i])
{
return 1;
}
else if(dest[i]<src[i])
{
return -1;
}
else
{
i++;
}
}
}
对strncmp函数进行封装:
int strncmp_s(char *dest,char *src,int len)
{
int i;
for(i=0;i<len;i++)
{
if(dest[i]>src[i])
{
return 1;
}
if(dest[i]<src[i])
{
return -1;
}
if(dest[i]==' '||src[i]==' ')
{
break;
}
}
return 0;
}
三.strtok;字符切割函数
strtok函数的格式:
char *strtok(char *str, const char *delim);
对strtok函数进行封装:
char *strtok_s(char *src,char *sub)
{
int i =0;
int count = 0;
while(src[i]!= '\0')
{
if(src[i]=='')
{
count++;
}
i++;
}
char *psrc[count+1]= {NULL};
i = 0;
int index = 0;
psrc[index] = src;
while(src[i]!='\0')
{
if(src[i]!=sub)
{
src[i] = '\0';
index++;
psrc[index] = src[i+1];
}
i++;
}
}
代码展示:
int main()
{
char src[20] = "prid evil";
char *psrc = NULL;
psrc = strtok(src," ");
printf("%s\n",psrc);
// psrc = strtok(NULL," ");
// printf("%s",psrc);
while(psrc != NULL)
{
psrc = strtok(NULL," ");
printf("%s\n",psrc);
}
return 0;
}
输出结果为:
?
四.strchr与strrchr;字符查找函数
strchr与strrchr函数的格式:
char *strchr(const char *str, int c);
char *strrchr(const char *str, int c);
对strchr函数进行封装:
char *strchr_s(char *src,int a)
{
int i = 0;
while(src[i]!= '\0')
{
if(src[i]==a){
return &src[i];
}
i++;
}
}
对strrchr函数进行封装:
char *strrchr_s(char *src,int a)
{
int i = 0;
int n = strlen(src);
while(src[n-1-i]!='\0')
{
if(src[n-1-i]==a)
{
return &src[n-1-i];
}
i++;
}
}
五. strpbrk,strstr,strcspn,strspn 字符串查找函数;
strpbrk的定义格式:char *strpbrk(const char *str1, const char *str2);
对strpbrk函数进行封装:
?
strstr的定义格式:char *strstr(const char *haystack, const char *needle);
对strstr函数进行封装:
char *strstr_s(char *src,char *sub)
{
int i = 0;
while(src[i]1!='\0')
{
if(src[i]==sub[0]&&src[i+1]==sub[1]&&src[i+2]==sub[2])
{
return &src[i];
}
i++;
}
return NULL;
}
strcspn的定义格式:size_t strcspn(const char *str1, const char *str2);
strspn的定义格式:size_t strspn(const char *str1, const char *str2);
SUMMARY:
今天对字符以及字符串的处理的函数进行了学习,老师课堂上也对系统自带的函数带着大家进行了自行封装,理解运行逻辑,更好的学习了解了其中的运行逻辑,不过今天的知识点些许多,还需要课下进行消化。
|