C库函数学习(一) <string.h>

来源:互联网 发布:sql insert 限制 编辑:程序博客网 时间:2024/04/30 19:41

  1. strlen:返回字符串的长度(0值表示字符串结尾)size_t strlen( char *str );必须保证字符串以0结尾,否则函数会一直检查,直到遇见0为止,如果至字符串的结尾仍没有检查到0,则会越界检查,但它不会改变越界内存的值。
  2. strcpy:把from所指由'\0'结束的字符串复制到to所指的数组中
    char *strcpy( char *to, const char *from );目的字符串的长度应该大于源串的长度,否则strcpy复制的长度仍然是源串的长度(通过0来确定),此时就可能会覆盖掉其他内存中的值,若此内存保存数据,则是灾难性的。
  3. strncpy:将字符串from中从第一个开始最多n个字符复制到字符数组to中
    char *strncpy( char *to, const char *from, size_t count );strncpy并不会填补to所指字符串的最后的元素为0,需要我们自己处理;也可能溢出覆盖掉其他内存。
  4. strcmp:字符串比较函数。比较两个以0结尾的字符串的大小
    int strcmp( const char *str1, const char *str2 );如果str1>str2,返回大于0的值。如果str1=str2,返回0。如果str1<str2,返回小于零的值。如果串没有结尾,即最后的字符的ASII的值不为0,则会越界判断。
  5. strncmp:字符串比较函数。比较两个字符串前n个字符的大小。
    int strncmp( const char *str1, const char *str2, size_t count );
    当count大于某一个串的长度时,当遇到0字符时,比较自动停止,则长串大于短串。返回值同strcmp。
    如果串没有结尾,即最后的字符的ASII的值不为0,则会越界判断。
  6. strcat:将一个str2字符串添加至str1后边。
    strncat:将一个str2字符串的前n个字符添加至str1后边。
    char *strcat( char *str1, const char *str2 );
    char *strncat( char *str1, const char *str2, size_t count );
    一定保证str1的长度大于str1和str2的长度之和,否则可能会发生溢出和内存覆盖。
  7. strchr:返回字符串(0值表示字符串结尾)中第一个ASII的值等于ch的字符的指针,若没有找到返回NULL。
    strrchr:返回字符串(0值表示字符串结尾)中最后一个ASII的值等于ch的字符的指针,若没有找到返回NULLchar *strchr( const char *str, int ch );
    char *strrchr( const char *str, int ch );
  8. strstr:在str1串中查找str2字符串的第一次出现的位置,没找到则返回NULL。
    char *strstr( const char *str1, const char *str2 );
  9. strcspn:The function strcspn() returns the index of the first character in str1 that matches any of the characters in str2. 如果没找到则返回str1的最后一个字符,即结尾标志字符'\0'的索引。
    size_t strcspn( const char *str1, const char *str2 );
  10. strspn:The strspn() function returns the index of the first character in str1 that doesn't match any character in str2
    如果没找到则返回str1的最后一个字符,即结尾标志字符'\0'的索引。
    size_t strspn( const char *str1, const char *str2 );
  11. strpbrk:The function strpbrk() returns a pointer to the first ocurrence in str1 of any character in str2, or NULL if no such characters are present. 
    char *strpbrk( const char *str1, const char *str2 );
  12. strtok:(怎么实现的呢?竟然只用了一个指针!!!)

    The strtok() function returns a pointer to the next "token" in str1, where str2 contains the delimiters that determine the token. strtok() returns NULL if no token is found. In order to convert a string to tokens, the first call to strtok() should have str1 point to the string to be tokenized. All calls after this should have str1 be NULL

    char *strtok( char *str1, const char *str2 );
    //示例:#include<stdio.h>#include<string.h>#include <stdlib.h>int main(){char str[]="this  is  a  string";char *s;s=strtok(str," ");while(s!=NULL){puts(s);s=strtok(NULL," ");}return 0;}
    则程序输出每个单词,即:this、is、a、string


原创粉丝点击