博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

字符串常用处理函数

Posted on 2011-08-12 11:40  yuanzfy  阅读(474)  评论(0)    收藏  举报

strtok

      函数原型char *strtok(char *_str, const char *_delim);

      函数功能是用分隔符集分割一个字符串,并且得到每一个子串

char *s="how to use it";
char *d=" ";
char *p;
p=strtok(s,d);
while(p)
{
    printf("%s\n",s);
    p=strtok(NULL,d);
}
 
程序输出
how
to
use
it
需要注意的是,_delim参数是一个分割字符集,函数按照单个字符分割,而不是delim整个串
就是说,对于本例,如果d=” o”,则会使用’ ‘和’o’两个分隔符,程序输出如下:
h
w
t
use
it
 

strstr

      函数原型char *_cdecl strstr(char *_Str,const char *_Substr);

      函数功能是在第一个字符串中查找第二个字符串,并且返回第一次出现第二个字符串的地址。

      用法简单,不再详述。

 

strcat_s

      函数原型errno_t_cdecl strcat_s(char * _Dst, rsize_t _SizeInbytes, const char* _Src);

                  errno_t_cdecl strncat_s(char * _Dst, rsize_t _SizeInbytes, const char* _Src,rsize_t_MaxCount);

      函数功能是拼接_Src到_Dst,第二个参数是目标字符串_Dst长度,第四个参数是拼接最大长度,就是最多把_Src中多少个字符拷贝到_Dst中。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main( void )
{
   char string[80];
   // using template versions of strcpy_s and strcat_s:
   strcpy_s( string, "Hello world from " );
   strcat_s( string, "strcpy_s " );
   strcat_s( string, "and " );
   // of course we can supply the size explicitly if we want to:
   strcat_s( string, _countof(string), "strcat_s!" );
   printf( "String = %s\n", string );
}

      程序输出

      String = Hello world from strcpy_s and strcat_s!

sprintf_s

      函数原型int sprintf_s( char *buffer, size_t sizeOfBuffer, const char *format [, argument] ... );

      函数功能是将数据格式化输出到字符串。

#include <stdio.h> 
int main( void ) 
{ 
     char buffer[200], s[] = "computer", c = 'l'; int i = 35, j;
     float fp = 1.7320534f; // Format and print various data:
     j = sprintf_s( buffer, 200, " String: %s\n", s ); 
     j += sprintf_s( buffer + j, 200 - j, " Character: %c\n", c ); 
     j += sprintf_s( buffer + j, 200 - j, " Integer: %d\n", i ); 
     j += sprintf_s( buffer + j, 200 - j, " Real: %f\n", fp ); 
     printf_s( "Output:\n%s\ncharacter count = %d\n", buffer, j ); 
}

      程序输出:

      String: computer

      Character: l

      Integer: 35

      Real: 1.732053

 

      character count = 79