当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
C语言字符串几个常用函数小结
发布时间:2010/5/17 11:17:27 来源:城市学习网 编辑:ziteng
  字符串处理函数
  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、字符串复制函数:strcpy、strncpy
  char *strcpy(char *dest, const char *src);
  4、字符串连接函数: strcat
  char *strcat(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 [NextPage]   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、搜索字符在串中第一次出现的位置strchr
  pdest = strchr( string, ch );
  在string中搜索ch,返回str在string中第一次出现的位置
  8、字符串部分拷贝 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个字符
  9、字符串大小写转换函数: strlwr、strupr
  补充:这些函数都要求 #include <string.h>
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved