字符串函数

来源:互联网 发布:淘宝客如意投推广店铺 编辑:程序博客网 时间:2024/06/05 08:11

strcpy字符串复制

Copy a string.

char *strcpy( char *strDestination, const char *strSource );

strcpy把从strSource地址开始且含有’\0’结束符的字符串复制到以strDestination开始的地址空间,返回值的类型为char*。

#include <string.h>#include <stdio.h>void main( void ){   char string[80];   strcpy( string, "Hello world!" );   printf( "String = %s\n", string );}

Output

String = Hello world!


strcmp字符串比较

Compare strings.

int strcmp( const char *string1, const char *string2 );

若string1==string2,则返回零;

若string1 < string2,则返回负数;

若string1 > string2,则返回正数。

即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。


strcat字符串连接

Append a string.

char *strcat( char *strDestination, const char *strSource );

strSource字符串先去掉strDesination字符串末尾的结束符,再连接到末尾,不检测是否溢出,所以目标字符串大小得控制好

#include <string.h>#include <stdio.h>void main( void ){   char string[80];   strcpy( string, "Hello world from " );   strcat( string, "strcpy " );   strcat( string, "and " );   strcat( string, "strcat!" );   printf( "String = %s\n", string );}

Output

String = Hello world from strcpy and strcat!


strstr查找子串

Find a substring.

char *strstr( const char *string, const char *strCharSet );

从字符串string中查找是否有字符串strCharSet,如果有,返回第一次满足条件时子串首字符的指针,如果没有,返回null。

#include <string.h>#include <stdio.h>char str[] =    "lazy";char string[] = "The quick brown dog jumps over the lazy fox";void main( void ){   char *pdest;   int  result;   pdest = strstr( string, str );   result = pdest - string + 1;   if( pdest != NULL )      printf( "%s found at position %d\n\n", str, result );   else      printf( "%s not found\n", str );}

Output

lazy found at position 36


stcchr查找字符

Find a character in a string.

char *strchr( const char *string, int c );

查找字符串string中首次出现字符c的位置

返回值:返回首次出现c的位置的指针,返回的地址是被查找字符串指针开始的第一个与c相同字符的指针,如果不存在,则返回NULL。

原创粉丝点击