字符串处理函数

小甲鱼温馨提示:size_t 被定义于 stddef.h 头文件中,它事实上就是无符号整形(unsigned int)

strlen计算字符长度

#include<stdio.h>
#include<string.h>

int main()
{
      char str[]="I love FishC.com!";
      printf("sizeof str=%d\n",sizeof(str));
      printf("strlen str=%u\n",strlen(str));

    return 0;
}

sizeof str=18
strlen str=17

所以用u,用d也行

长度指的是字符的个数,不包括反斜杠0,而sizeof(尺寸)包括

拷贝字符串:strcpy和strncpy

#include<stdio.h>
#include<string.h>

int main()
{
      char str1[]="original string";
      char str2[]="new string";
      char str3[100];

      strcpy(str1,str2);
      strcpy(str3,"copy successful");
      printf("str1:%s\n",str1);
      printf("str2:%s\n",str2);
      printf("str3:%s\n",str3);
    return 0;
}

结果

str1:new string
str2:new string
str3:copy successful

左边str1是目标字符数组,右边str2是原数组,str1长度足以容纳str2,否则会出现问题

#include<stdio.h>
#include<string.h>

int main()
{
      char str1[]="To be or not to be";
      char str2[40];

      strncpy(str2,str1,5);
      str2[5]='\0';
      printf("str2:%s\n",str2);
    return 0;
}

结果

str2:To be

5是限制字符数,结尾系统没有自动加反斜杠0,要加上!

 连接字符串:strcat和strncat

#include<stdio.h>
#include<string.h>

int main()
{
      char str1[]="I love";
      char str2[]="FishC.com!";

      strcat(str1," ");
      strcat(str1,str2);
      printf("str1:%s\n",str1);
    return 0;
}

结果

str1:I love FishC.com!

备注:strn总是要加反斜杠0

比较字符串:strcmp和strncmp

#include<stdio.h>
#include<string.h>

int main()
{
      char str1[]="FishC.com!";
      char str2[]="FishC.com!";

      if (!strcmp(str1,str2))
      {
          printf("两个字符串完全一致!\n");
      }
      else
      {
          printf("两个字符串存在差异!\n");
      }
    return 0;
}

结果

两个字符串完全一致!

 

posted @ 2021-08-19 11:33  好想成为一只鸟  阅读(172)  评论(0)    收藏  举报