C语言中自带的字符串处理函数与printf不不同的是,这些函数并不在头文件stdio.h中,而是在字符串专用的头文件string.h中。
因此,如果要处理字符串处理函数,应现在代码的顶端加上#include <string.h>。
获取字符串长度strlen
strlen函数可以获取字符数组中的字符串长度,它从第一个字符开始计数,知道遇到\0为止,并返回累计的长度。
函数原型:
size_t strlen (const char* str);
函数的输入const char* str是一个指向字符串首地址的指针;
如果输入参数不是const指针,将会被转化成const指针。
这里使用const有两个意义:
1.保证函数内部不会修改指针指向的字符
2.提示使用者。字符串不会被修改
函数的输出size_t是一个size_t类型的整型,用于表示字符串长度。
size_t并不是一个新的关键词,它是已有整型变量的别名,有可能是unsigned int,unsigned long,unsigned longlong类型,这取决于编译器是怎样实现的。
同时,sizeof关键词返回的结果也是size_t类型。
#include <stdio.h>
#include <string.h>
int main()
{
char str[20] = "hello";
size_t size = sizeof(str);//测量数组本身空间大小
printf("sizeof=%d\n", size);
size_t len = strlen(str);//测量字符串长度
printf("len=%d\n", len);
return 0;
}
结果为
sizeof=20
len=5
字符串拼接函数strcat
将源字符串拼接到目标字符串后面。
函数原型:
char* strcat (char* destination,const char* source);
函数有两个输入,char* destination是拼接目标字符串首地址,const char* source是拼接源字符串首地址。
函数的输出是char*destination拼接目标字符串首地址。
#include <stdio.h>
#include <string.h>
int main()
{
char dest[9] = "HI";
char src[5] = "美女";
printf("%s\n", dest);
printf("%s\n\n", src);
strcat_s(dest, src);
printf("%s\n", dest);
printf("%s\n", src);
return 0;
}
结果为
HI
美女
HI美女
美女
值得注意的是,拼接完毕后的目标数组的元素要小于等于数组元素。
字符串复制函数strcpy
将源字符串的内容复制到目标字符串中。
strcpy函数会从首元素开始覆盖目标字符串。
函数原型:
char* strcpy (char* destination,const char* source);
char* destination输入是复制目标字符串首地址,const char* source输入是复制源字符串首地址。
函数的输出是char*destination复制目标字符串首地址。
#include <stdio.h>
#include <string.h>
int main()
{
char dest[9] = "HI";
char src[5] = "美女";
printf("%s\n", dest);
printf("%s\n\n", src);
strcpy_s(dest, src);
printf("%s\n", dest);
printf("%s\n", src);
return 0;
}
结果为
HI
美女
美女
美女
字符串比较函数strcmp
用于比较两个字符串,若一致则返回0。
函数原型:
int* strcmp (char* destination,const char* source);
char* destination输入是待比较字符串1的首地址,const char* source输入是待比较字符串2的首地址。
函数的输出是int*destination,如果两个字符串一致,则返回0,否则返回其他值。
若不一致,比较当前字符的ASCII码大小。小于则返回-1,大于则返回1。
#include <stdio.h>
#include <string.h>
int main()
{
const char* str1 = "abcdefg";
const char* str2 = "abcdefgh";
const char* str3 = "abcdef";
int ret = strcmp(str1, str1);
printf("%d\n", ret);
ret = strcmp(str1, str2);
printf("%d\n", ret);
ret = strcmp(str1, str3);
printf("%d\n", ret);
return 0;
}
结果为
0
-1
1
只有满怀自信的人,才能在任何地方都怀有自信地沉浸在生活中,并实现自己的意志。