字符串函数头文件 string.h
1· strlen
· size_t strlen(const char*s);
· 返回s的字符串长度(不包含结尾的0)
#include <stdio.h>
#include <string.h>
int main(int argc,char const *argv[])
{
char line[] = "hello";
printf ("strlen=%lu\n",strlen(line));//strlen=5
printf ("sizeof=%lu\n",sizeof(line));//sizeof=6
return 0;
}
2· strcmp
·int strcmp(const char*s1,const char*s2);
·比较两个字符串,返回:
·0:s1==s2
·1:s1>s2
·-1:s1<s2
#include <stdio.h>
#include <string.h>
int main(int argc,char const *argv[])
{
char s1[]="abc";
char s2[]="abc";
printf ("%d\n",strcmp(s1,s2));//0
return 0;
}
3· strcpy
· char*strcpy(char *restrict dst,const char *restrict src);
·把src的字符串拷贝到dst
·restrict表明src和dst不重叠(c99)
·返回dst
·为了能链起代码来
#include<string.h>
#include <stdio.h>
void main()
{
char a1[10];
char a2[] = "hello world!";
strcpy(a1, a2);
printf("a1=%s\n", a1);//a1=hello world!
printf("a2=%s\n", a2);//a2=hello world!
}
#include <stdio.h>
void main()
{
char a1[10]="aaa";
char a2[] = "hello world!";
strcpy(a1, a2);
printf("a1=%s\n", a1);//a1=hello world!(会覆盖掉原来的字符)
printf("a2=%s\n", a2);//a2=hello world!
}
4· strcat
·char *strcat(char *restrict s1,const char *restrict s2);
·把s2拷贝到s1的后面,接成一个长的字符串
·返回s1
·s1必须有足够的空间
#include<string.h>
#include <stdio.h>
void main()
{
char a1[]="hello";
printf ("%d\n",strlen(a1));//5
char a2[] = " world!";
strcat(a1, a2);
printf("a1=%s\n", a1);//a1=hello world!
printf("a2=%s\n", a2);//a2= world!
printf ("%d",strlen(a1));12
}
5· strchr
strchr函数功能为在一个串中查找给定字符的第一个匹配之处。函数原型为:char *strchr(const char *str, int c),即在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。strchr函数包含在C 标准库 <string.h>中。
str-- 要被检索的 C 字符串。
c-- 在 str 中要搜索的字符。
返回一个指向该字符串中第一次出现的字符的指针,如果字符串中不包含该字符则返回NULL空指针。
·char *strchr( const char *string, int c );
#include <stdio.h>
#include <string.h>
int main ()
{
const char a1[] = "hello world!";
const char a2 = 'e';
char *r;
r = strchr(a1, a2);
printf("%s\n",r);//llo wold!
return(0);
}
6· strstr
在一个字符串中找另一个字符串(查找字符串)
strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回 str1字符串从 str2第一次出现的位置开始到 str1结尾的字符串;否则,返回NULL。
返回值是指针,返回的是子字符串在原先字符串中第一次出现的位置,如果没有找到的话,就返回NULL
·char *strstr( const char *string, const char *strCharSet );
#include<stdio.h>
#include<string.h>
int main()
{
char a1[] = "hello world!";
char a2[] = "llo";
char *r = strstr(a1, a2);
if (r == NULL)
{
printf("不存在\n");
}
else
{
printf("%s\n", r);//llo world!
}
return 0;
}