您的位置:首页 > 编程语言 > C语言/C++

C语言字符串几个常用函数

2013-03-20 09:31 393 查看
字符串处理函数   1、将格式化数据写入字符串:sprintf

  int sprintf( char *buffer, const char *format, ... );

  将数据打印到buffer中

  例如:char result[100];

  int num = 24;

  sprintf( result, "%d", num );

  例如:char string[50];

  int file_number = 0;

  sprintf( string, "file.%d", file_number );

  file_number++;

  output_file = fopen( string, "w" );

  又例如:char result[100];

  float fnum = 3.14159;

  sprintf( result, "%f", fnum );

  2、字符串长度查询函数: strlen

  int strlen(const char *s);

  3、字符串连接函数: strcat

  char *strcat(char *dest, const char *src);

  4、字符串复制函数:strcpy、strncpy

  char *strcpy(char *dest, const char *src);

  5、字符串比较函数: strcmp、strncmp、stricmp、strnicmp

  字符串比较函数strcmp(分大小写)

  int strcmp(const char *s1, const char *s2);

  Return Value

  Return value

  Explanation

  less than 0

  str1 is less than str2

  equal to 0

  str1 is equal to str2

  greater than 0

  str1 is greater than str2''

  字符串搜索函数: strcspn、strspn、strstr、strtok、strchr

  6、查找子串strstr

  char *strstr(char *s1, char *s2);

  查找给定字符串在字符串中第一次出现的位置,返回位置指针

  如果找到,返回指针,指向s1中第一次出现s2的位置

  如果找不到,返回 NULL

  pdest = strstr( string, str );

  在string中搜索str,返回str在string中第一次出现的位置

  例如:char* str1 = "this is a string of characters";

  char* str2 = "a string";

  char* result = strstr( str1, str2 );

  if( result == NULL ) printf( "Could not find '%s' in '%s'\n", str2, str1 );

  else printf( "Found a substring: '%s'\n", result );

  输出结果为:Found a substring: 'a string of characters'

  7、字符串部分拷贝 strncpy, 字符串全部拷贝strcpy

  char *strncpy(char *dest, char *src, int maxlen);

  char *strcpy(char *dest, char *src);

  将前 maxlen 个字符从src拷贝到dest

  1)如果src中字符不足 maxlen 个,则连’\0’一起拷贝,’\0’后面的不拷贝

  2) 如果src中字符大于等于maxlen个,则拷贝 maxlen个字符

  8、搜索字符在串中第一次出现的位置strchr

  pdest = strchr( string, ch );

  在string中搜索ch,返回str在string中第一次出现的位置

  9、字符串大小写转换函数: strlwr、strupr

  补充:这些函数都要求 #include <string.h>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: