库函数(C)

本文最后更新于:2022年10月26日 凌晨

本文主要记录一些常用的C语言库函数,持续更新。

1 目录

函数 说明 手册链接
sprintf 把格式化的数据写入某个字符串 链接
strcmp 比较两个字符串 链接
qsort 快速排序 链接
strcat 拼接字符串 链接
strstr 查找子串 链接

2 库函数

2.1 sprintf

  • 头文件:stdio.h
  • 声明:int sprintf(char *string, char *format [,argument,…]);
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    #include <stdio.h>
    int main ()
    {
    char buffer [50];
    int n, a=5, b=3;
    n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
    printf ("[%s] is a string %d chars long\n",buffer,n);
    return 0;
    }

2.2 strcmp

  • 头文件:string.h
  • 声明:int strcmp ( const char * str1, const char * str2 );
  • 说明:比较两个字符串,如果小于则为负,大于为正,等于为0,两个字符串的比较是从左到右逐个比较,直到不同或找到’\0’为止。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    #include <string.h>
    int main(void)
    {
    char *a="123";
    char *b="321";
    int ret = strcmp(a.b);
    return 0;
    }

2.3 qsort

  • 头文件:stdlib.h
  • 声明:void qsort (void* base, size_t num, size_t size,int (compar)(const void,const void*));
  • 说明:如果compar返回值小于0(< 0),那么p1所指向元素会被排在p2所指向元素的左面
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #include <stdio.h>      /* printf */
    #include <stdlib.h> /* qsort */

    int values[] = { 40, 10, 100, 90, 20, 25 };

    int compare (const void * a, const void * b)
    {
    return ( *(int*)a - *(int*)b );
    }

    int main ()
    {
    int n;
    qsort (values, 6, sizeof(int), compare);
    for (n=0; n<6; n++)
    printf ("%d ",values[n]);
    return 0;
    }

2.4 strcat

  • 头文件:string.h
  • 声明:char * strcat ( char * s1, const char * s2 );
  • 说明:在s1后面添加s2
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #include <stdio.h>
    #include <string.h>

    int main ()
    {
    char str[80];
    strcpy (str,"these ");
    strcat (str,"strings ");
    strcat (str,"are ");
    strcat (str,"concatenated.");
    return 0;
    }

2.5 strstr

  • 头文件:string.h
  • 声明:char * strstr (char * str1, const char * str2 );
  • 说明:判断str2是否为str1的子串,不是则返回空
  • 示例
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #include <stdio.h>
    #include <string.h>

    int main ()
    {
    char str[] ="This is a simple string";
    char * pch;
    pch = strstr(str,"simple");
    if (pch != NULL)
    printf("1111");
    else
    printf("222");
    return 0;
    }

库函数(C)
https://blog.kala.love/posts/3e523d95/
作者
Lissettecarlr
发布于
2021年4月12日
许可协议