字符串操作函数(1)

1.字符串常见的API(函数调用的接口)
对字符串进行操作的时候要包含#include <string.h>的头文件

(1)puts
puts类似于ptintf,作用是输出字符串。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
	char  *str="C语言你好!";
    puts(str);
	system("pause");
	return 0;
}

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
	char  *str="C语言你好!";
	printf("%s\n",str);
    
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述
puts和printf的区别:
两者的区别在于,puts输出完字符串并自动换行,printf只有在\n(C语言换行符)的时候才能换行。

(2)gets
gets类似与scanf,作用是输入字符串

注意:当用scanf来输入字符串的时候,如果不定义字符串的空间大小,可能出现段错误。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char  pstr[128]={'\0'};
    //定义pstr,设置空间为128个字节,把每个元素都初始化为\0
    
    printf("请输入字符串:\n");
    gets(pstr);
    puts(pstr);
    
	system("pause");
	return 0;
}

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

char pstr[128]={’\0’},在内存当中做了什么事?

在内存当中,申请了连续的128个字节,每一项初始化都为\0。

char *pstr; 定义了一个char型的指针变量,存放的是别人的地址,在

windows下为4个字节,在linux下为8个字节。到底存放是谁的地址,

就不知道了,我们称之为野指针。造成非法内存访问,cmd窗口闪退。

(3)我们要为指针开辟空间:
开辟空间的例子:
pstr=(char *)malloc(128);//开辟空间为128个字节。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char  *pstr;//定义指针
    pstr=(char *)malloc(128);//申请空间为128个字节。
    memset(pstr,'\0',128);//初始化
    
    printf("请输入字符串:\n");
    gets(pstr);
    puts(pstr);
    
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述
memset(pstr,’\0’,128);
1.pstr 初始化的对象
2.初始化成什么字符,一般写‘\0’
3.初始化为多大

(4)用malloc申请空间的时候,可能会失败,要做判断

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char  *pstr;//定义指针为空
    pstr=(char *)malloc(128);//申请空间为128个字节。
    if(pstr==NULL)
    {
        printf("申请内存失败\n");
        exit(-1);    
    }
    
    memset(pstr,'\0',128);
    printf("请输入字符串:\n");
    gets(pstr);
    puts(pstr);
    
	system("pause");
	return 0;
}

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

——@上官可编程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值