C语言字符串库函数(strlen、strcmp、strcpy、strcat、atoi)全解

C语言中常用的字符串函数有以下几种:

函数格式 含义
strlen(s) 检测字符串实际长度
strcmp(s1,s2) 比较两个字符串长度
strcpy(s1,s2) 将s2复制到s1
strcat(s1,s2) 将s2拼接到s1后面
atoi(s1) 将字符串转换成整型数

一、字符串长度检测

#include <stdio.h>
int main()
{
	char s1[]="hello,world";
	printf("%d",strlen(s1));
	return 0;
}

运行结果
在这里插入图片描述
二、比较两个字符串的长度

#include <stdio.h>
int main()
{
	char s1[]="hello,";
	char s2[]={'w','o','r','l','d'};
	printf("%d",strcmp(s2,s1));
	return 0;
}

运行结果
在这里插入图片描述
三、将一个字符串复制到另一个字符串

#include <stdio.h>
int main()
{
	char s1[]="hello,";
	char s2[]={'w','o','r','l','d'};
	printf("复制前:S1=%s,S2=%s\n",s1,s2);
	strcpy(s1,s2);
	printf("复制后:S1=%s,S2=%s",s1,s2);
	return 0;
}

运行结果
在这里插入图片描述
四、两个字符串拼接

#include <stdio.h>
int main()
{
	char s1[]="hello,";
	char s2[]={'w','o','r','l','d'};
	strcat(s1,s2);
	printf("%s",s1);
	return 0;
}

运行结果
在这里插入图片描述
五、将字符串转换成整型数

#include <stdio.h>
int main()
{
	char s1[]="123456";
	printf("%d",atoi(s1));
	return 0;
}

运行结果
在这里插入图片描述
当然如果你是对字符串转数字就是另外一个情况了

#include <stdio.h>
int main()
{
	char s1[]="hello,world";
	printf("%d",atoi(s1));
	return 0;
}

运行结果
在这里插入图片描述

原创文章 55 获赞 17 访问量 3661

猜你喜欢

转载自blog.csdn.net/qq_42942881/article/details/104894364