字符串操作函数

gets()             //获取字符串
puts()             //输出字符串
memset()           //初始化内存
strcpy()           //字符串的拷贝
strcat()           //字符串的拼接
strcmp()           //字符串的比较

以上就是我之前所学到的字符串操作函数,现在来一一总结。

1.gets()和puts()

     gets()的作用是从键盘上读取字符串,值到回车结束。(回车符不属于字符串)我又查了与scanf的区别:scanf碰到回车、空格、Tab都会结束。
     gets()函数的用法:gets(s);  //s表示字符串
     但是在最新的vs中使用gets()会报错,因此我们应使用gets_s(s);

     例子:

#include<stdio.h>
int main() {
	char str[20]={0};
	gets_s(str);     //例如输入一个abc
	printf("%s", str);
	return 0;
}

    运行结果: 

     puts()的作用是输出字符串并换行。与printf的用法类似。
     puts()的用法:puts(s); //s表示字符串
     例子:

#include<stdio.h>
int main() {
	char str[20]={0};
	gets_s(str);//输入abc
	puts(str);//输出abc
	return 0;
}

   运行结果: 

2.memset()函数

     memset是计算机中C/C++语言初始化函数。作用是将某一块内存中的内容全部设置为指定的值, 这个函数通常为新申请的内存做初始化工作。
     头文件为:#include<string.h>
memset函数的一般使用格式为
 

memset(首地址,值,sizeof(地址总大小));

例如:

char arr[256];
memset(arr,1,sizeof[arr])  //按照字节初始化内存,等价于char arr={‘\0’};

3.strcpy()函数 

    strcpy函数的作用是把含有转义字符\0 空字符作为结束符,然后把src该字符串复制到dest。
头文件为:#include<string.h>

例子:

#include<stdio.h>
#include<string.h>
int main() {
	char dest[6] = "Hello";//原字符串,会被src替代
	char src[10] = "world\0";//src为要复制的字符串
	strcpy(dest, src);
	printf("%s", dest);
	return 0;
}

结果展示:

4.strcat()函数 

    strcat()函数的作用是将两个字符串拼接在一起并返回前一个字符串。调用strcat函数要包含的头文件为:#include<string.h>
例子:

#include<stdio.h>
#include<string.h>
int main() {
	char dest[6] = "Hello";
	char src[10] = "world";
	printf("%s", strcat(dest, src));//将会输出 Helloworld
	return 0;
}

结果展示:

 5.strcmp()函数

      strcmop函数的作用是比较两个字符串str1和str2是否相同,如果相同则返回0,如果不同,前者大于后者则返回1,否则返回-1.头文件为:#include<string.h>
简单示例:1.相同输出0

#include<stdio.h>
#include<string.h>
int main() {
	char a[10] = "hello";
	char b[10] = "hello";
	printf("%d", strcmp(a, b));//将会输出0
	return 0;
}

结果展示:

     2.前者大于后者输出1
 

#include<stdio.h>
#include<string.h>
int main() {
	char a[10] = "hello";
	char b[10] = "hell";
	printf("%d", strcmp(a, b));//将会输出1
	return 0;
}

 3.后者大于前者输出-1
 

#include<stdio.h>
#include<string.h>
int main() {
	char a[10] = "hell";
	char b[10] = "hello";
	printf("%d", strcmp(a, b));//将会输出-1
	return 0;
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清酒。233

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值