天天看点

C语言常用函数总结

有时候需要用一些C库函数但是,库函数相似的太多了,记着记着就记忆混淆了,特此总结一下,愿与诸君共享

#include “stdio.h”

sprintf函数

功能:向一个字符串内格式化输入

char buf[1024]={0};
char buf1[5]="zxcv";
char buf2[5]="bnma";
sprintf(buf,"123 %s %s",buf1,buf2);
printf("%s\n",buf);

运行结果:123 zxcv bnma

           

sscanf函数

功能:从字符串中格式化输出到另一个字符串

char buf[5]={0};
   char buf1[20]="zxcvbmn";
   char buf2[5]={0};
   sscanf(buf1,"%s%s",buf,buf2);
   printf("%s\n",buf);
   printf("%s\n",buf2);
运行结果:
	buf:zxcvbnm
	buf2:
           
char buf[5]={0};
   char buf1[20]="zxcvbmn";
   char buf2[5]={0};
   sscanf(buf1,"%s%s",buf,buf2);
   printf("%s\n",buf);
   printf("%s\n",buf2);
运行结果:
	buf:zxcv
	buf2:bnm
           
char buf[5]={0};
   char buf1[20]="zxcvbmn";
   char buf2[5]={0};
   sscanf(buf1,"%2s%2s",buf,buf2);
   printf("%s\n",buf);
   printf("%s\n",buf2);
运行结果:
	buf:zx
	buf2:cv
           

类比sprintf和sscanf 简单来说,sprintf可以多个字符串中截取合成任意一个字符串,sscanf只能从一个已知的字符串中任意截取多个字符串,一裁多

#include <string.h>

strcpy函数和strncpy函数

函数功能:字符串拷贝

strcpy

char buf[10]={0};
   char buf1[10]="zxcvbnm";
   strcpy(buf,buf1);
   printf("%s\n",buf);
运行结果:
      buf:zxcvbnm
           

strncpy

char buf[10]={0};
   char buf1[10]="zxcvbnm";
   strncpy(buf,buf1,3);
   printf("%s\n",buf);
运行结果:
     buf:zxc
           

#include “string.h”

strcat函数与strncat函数

函数功能:字符串的追加写

strcat

char buf1[10]="zxcv";
   char buf2[5]="bnm";
   strcat(buf1,buf2);
   printf("%s\n",buf1);
运行结果:
   buf1:zxcvbnm
           
char buf1[10]="zxcv";
   char buf2[5]="bnm";
   strncat(buf1,buf2,2);
   printf("%s\n",buf1);
   return 0;
运行结果:
   buf1:zxcvbn
           
char buf1[10]="zxcv";
   char buf2[5]="zxcv";
   if(strcmp(buf1,buf2)==0)
   {
       printf("两字符串相等\n");
   }
   else
   {
       printf("两字符串不相等\n");
   }
运行结果:
   两字符串相等
           
char buf1[10]="zxcv";
   char buf2[5]="zxcv";
   if(strncmp(buf1,buf2,3)==0)//只比较前三个字符
   {
       printf("两字符串相等\n");
   }
   else
   {
       printf("两字符串不相等\n");
   }
运行结果:
   两字符串相等