字符串函数小结---老是忘记

来源:互联网 发布:iphone铃声设置mac 编辑:程序博客网 时间:2024/04/28 15:52

  都在库 string.h 当中,一些常用的字符串函数。


  strlen (string s) ; 返回字符串s的长度


  strcat  ( string s1, string s2 ) ;  将字符串s2的一份拷贝添加到第一个字符串s1的结尾,字符串s1变成了一个新的字符串,字符串s2没有改变。


  strncat ( string  s1, string  s2, int n  ) ; 在函数strcat中,并没有考虑 s1是否有足够的空间来容纳s2,可能导致字符串溢出到相邻存储单元。所以strncat函数,较之strcat更加谨慎。需要int  n来指明最多添加的字符的数目。例如,strncat ( s1, s2, 10 )将s2字符串中的内容添加到s1,直到加到第10个字符或者遇到空字符为止。


  strcmp ( string s1, string s2 ) ; 这个函数功能比较强大,需要特别注意。而且据说在不同的环境下,返回的值还不一样。具体需要调试才能应用。    如果两个字符串中的初始字符相同的话,一般说来,strcmp( )函数会一直往后查找,直到找到第一对不一致的字符。然后函数返回相应的值。

   strncmp( string s1, string s2 , int n ) ;  与strcmp ( string s1, string s2 ) ;的关系,就类似于  strcat  ( string s1, string s2 ) ;与strncat ( string  s1, string  s2, int n  ) ;的关系。


   strcpy ( )函数在字符串运算中的作用,等价于赋值运算符。函数声明是这样的:char *strcpy ( char * s1, const char *s2 );所以它返回的是第一个参数的值,既一个字符的地址。


   编写一个简单的程序,来查看各种用途:

#include<stdio.h>#include<string.h>/* * 测试查看函数: * strlen(string s) * strcat( string s1, string s2) * strncat( string s1, string s2, int n) * strcmp( string s1, string s2) * strncmp( string s1, string s2, int n ) * strcpy */int main ( void ){    char my_name[15] = "XiDaDa";    char her_name[15] = "JuLiSha";    printf("%d\n", strlen( my_name) );    printf("%s\n", strcat(my_name, her_name) );    printf("%d\n", strcmp(my_name, her_name) );    printf("%s\n", strcpy(my_name, her_name) );    return 0;}


  

0 0