1.获取字符串的长度函数
(测字符指针s指向的字符串中的字符个数,不包括’\0’)//遇到第一个’\0’就结束
头文件:#include
函数定义:size_t strlen(const char *s);
返回值:字符串中字符的个数
#include <stdio.h>
#include <string.h>
int main()
{
//用strlen()获取字符串的长度
char str[100] = “Hello”;
int length = strlen(str);
printf(“length = %d\n”,length);
return 0;
}
2.字符串拷贝函数
头文件:#include<string.h>
函数定义:char *strcpy(char *dest,char *src);
dest:为目的字符串 src:为源字符串
//用strcpy复制字符串
char str[16];
char src[16] = "Hello World";
strcpy(str,src);
printf("%s\n",str);
头文件:#include<string.h>
函数定义: char *strncpy(char *dest,char *src,size_t n);
//将src的前n位字符拷贝到的dest中
3.字符串追加函数
头文件:#include<string.h>
函数定义:char *strcat(char *dest,char *src);
char str[32] = "Hello";
char src[16] = "World";
strcat(str,src);
printf("%s\n",str);
头文件:#include<string.h>
函数定义:char *strncat(char *dest,char *src,size_t n);
追加src的前n个字节到dest,追加时会追加’\0’
4.字符串比较函数
头文件:#include<string.h>
函数定义:int strcmp(const char *s1,const char *s2);
返回值:如果指向s1的大于指向s2,则返回1;s1等于s2,则返回0;s1小于s2,则返回-1
char str[16] = "Hello";
char str2[16] = "Hello";
char str3[16] = "hello";
char str4[16] = "Gello";
printf("%d\n",strcmp(str,str2));
printf("%d\n",strcmp(str,str3));
printf("%d\n",strcmp(str,str2));
头文件:#include<string.h>
函数定义:int strncmp(const char s1,const char s2,size_t n);
//比较指向S1,S2的前n个字符
5.字符查找函数
头文件:#include
函数定义:char strchr(const char s,int c);//首次匹配
返回值:返回首次出现c的地址,如果不存在则返回NULL
char str[] = "Helloworld";
char *ret = strchr(str,'o');
if(ret != NULL)
{
printf("%d\n",ret-str);
}
头文件:#include
函数定义:char* strrchr(const char* s,int c);//首次匹配
6.字符串匹配函数
头文件:#include
函数定义:char* strstr(const char* hasstrck,const char *needle);
返回值:如果存在,则返回找到的字符串起始位置,否则返回NULL
char str[] = "123456123122";
char sgoal[] = "456";
char *ret = strstr(str,sgoal);
if(ret == NULL)
{
printf("没有找到\n");
}
else
{
printf("字符串其实位置在%d\n",ret-str);
}
7.字符串转换数值
头文件:#include<stdlib.h>
函数定义:int atoi(conset char* ptr);
头文件:#include<stdlib.h>
函数定义:long atol(conset char* ptr);
头文件:#include<stdlib.h>
函数定义:double atof(conset char* ptr);
char str[] = "1223";
int num = atoi(str);
printf("%d\n",num);
8.字符串切割函数
头文件:#include
函数定义:char* strtok(char* str,const char *delim);
char str[] = "1223";
int num = atoi(str);
printf("%d\n",num);*/
char str[] = "111:222:333";
char *ret;
ret = strtok(str,":");//第一次切割
printf("%s\n",ret);
//后面切割要将strtok的第一个参数传NULL
while ((ret = strtok(NULL,":")) !=NULL) {
printf("%s\n",ret);
}
9.格式化字符串操作函数
函数定义:int sprintf(const char*buf,const char format,…);//输出到buf指定内存区域
函数定义: int sscanf(const charbuf,const char *format,…);//从buf指定内存区域读入数据
char *str[30];
int a,b,c;
sprintf(str,"%d%d%d",2013,22,111);
printf("%s\n",str);
sscanf("333:22:11","%d:%d:%d",&a,&b,&c);
printf("a=%d,b=%d,c=%d\n",a,b,c);