一、strlen()函数
strlen()函数用于统计字符串的长度。
#include <stdio.h>
#include <string.h>
int main()
{
char *p = "hello world";
int len = strlen(p);
printf("p strlen[%d]\n", len);
return 0;
}
二、strcat()函数
strcat()用于拼接字符串,接收俩个字符串作为函数,把第二个字符串的备份附加在第一个字符串末尾,并把拼接后形成的新字符串作为第一个字符串,第二个字符串不变。strcat()函数的类型是char *(即指向char的指针),返回第一个参数的地址,即拼接第二个字符串后的第一个字符串的地址。
#include <stdio.h>
#include <string.h>
int main()
{
char ch1[20] = "Hello ";
char ch2[10] = "World";
//char *ch3;
printf("strcat前:ch1[%s],ch1指针[%p],ch2[%s],ch2指针[%p]\n", ch1, &ch1, ch2, &ch2);
char *ch3 = strcat(ch1,ch2);
printf("strcat后:ch1[%s],ch1指针[%p],ch2[%s],ch2指针[%p],ch3[%s],ch3指针[%p]\n", ch1, &ch1, ch2, &ch2, ch3, &ch3);
printf("strcat(ch1,ch2)[%p]\n", strcat(ch1,ch2));
return 0;
}
三、strncat()函数
strcat()函数无法检查第一个数组是否能容纳第二个字符串,如果分配给第一个数组的空间不够大,多出来的字符会溢出到相邻储存单元。
#include <stdio.h>
#include <string.h>
int main()
{
char ch1[20] = "Hello ";
char ch2[10] = "World";
printf("strincat前:ch1[%s],ch1指针[%p],ch2[%s],ch2指针[%p]\n", ch1, &ch1, ch2, &ch2);
char *ch3 = strncat(ch1,ch2,10);
printf("strncat后:ch1[%s],ch1指针[%p],ch2[%s],ch2指针[%p],ch3[%s],ch3指针[%p]\n", ch1, &ch1, ch2, &ch2, ch3, &ch3);
printf("strncat(ch1,ch2)[%p]\n", strncat(ch1,ch2,10));
return 0;
}
四、strcmp()函数
strcmp()函数比较俩个字符串的内容,不是字符串的地址。如果相同,返回0,不相同返回非0值。按照ASCII码比较,返回的是俩个参数的ASCII码之差。
#include <stdio.h>
#include <string.h>
int main()
{
char ch1[10] = "A";
char ch2[10] = "A";
char ch3[10] = "a";
int i1 = strcmp(ch1,ch2);
int i2 = strcmp(ch1,ch3);
printf("strcmp(ch1,ch2)=[%d]\n", i1);
printf("strcmp(ch1,ch3)=[%d]\n", i2);
return 0;
}
四、strncmp()函数
strcmp()函数比较字符串中的字符,知道发现不通的字符为止,这一过程可能到字符串的结尾。strncmp()函数可以比较字符不同的地方,也可以只比较第三个参数指定的字符数(第一个参数的第N位和第二个参数比较)。
五、strcpy()函数和strncpy()函数
strcpy()将第二个字符串参数复制给第一个字符串参数。返回的是第一个参数的值,即第一个参数的地址。
strncpy()函数为n,)将第二个字符串参数的前n位字符串复制给第一个字符串参数。
六、sprintf()函数
sprintf()函数声明在stdio.h,不在string.h。
sprintf()函数和printf()函数类型,sprintf()函数是把数据写入字符串中,而不是打印在显示器上。该函数可以把多个元素合成一个字符串。
七、其他函数
1、char *strchr(const char *s, int c);
如果s字符串包含c字符,该函数返回指向s字符串首位置的指针(末尾的空字符也是字符串的一部分,也在查找范围内),如果为找到,返回空指针。
2、char *strpbrk(const char *s1, const char *s2);
如果s1字符包含s2字符串中的任意字符,该函数返回指向s1字符串首位置的指针,如果在s1字符串中未找到任何s2字符串的字符,则返回空指针。
3、char *strrchr(const char *s, int c);
该函数返回s字符串找那个c字符的最后出现的位置(末尾的空字符也是字符串的一部分,也在查找范围内),如果为找到,返回空指针。
4、char *strstr(const char *s1, const char *s1)
该函数返回指向s1字符串中s2字符串出现的首位置,如果在s1中没有找到s2,则返回空指针。
5、size_t strlen(const char *s);
该函数返回字符串中的字符数,不包括末尾的空字符。