10.1 c++ 字符串处理函数

第十章 字符串处理函数

10.1 字符串操作函数

以str开头为字符串处理函数 默认遇到’\0’结束操作

10.1.1 测量字符串的长度 strlen

#include <string.h>
size_t strlen(const char *s);
s指 需要测量字符串的元首素地址
char str1[128] = "hello";
strlen(str1);//5

char str2[128] = "he\0llo";
strlen(str2);//2

10.1.2 字符串拷贝函数 strcpy

#include <string.h>
char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);
dest:目的空间地址
src: 原字符串的首元素地址
char dst[128] = "";
char src[] = "hello\0world";
strcpy(dst,src);

char dst1[] = ""; //dst1数组只有1字节 当src1拷贝到dst1中 造成溢出(内存污染)
char src1[] = "hello\0world";
strcpy(dst,src);
cout<<dst1<<endl;//hello world(污染内存)

10.1.3 字符串追加函数 strcat

char dst[128] = "hello";
char src[] = "world";
strcat(dst,src);
cout<<dst<<endl;//helloworld

10.1.4 字符串比较strcmp

#include <string.h>
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);

返回值:
>0	s1字符串 > s2字符串
<0	s1字符串 < s2字符串
==0	s1字符串 == s2字符串
char str1[128] = "";
char str2[128] = "";

cout<<"请输入第一个字符串:";
cin>>str1;
cout<<"请输入第二个字符串:";
cin>>str2;

if(strcmp(str1,str2)>0)
{
cout<<str1<<"大于"<<str2<<endl;
}
else if(strcmp(str1,str2)<0)
{
cout<<str1<<"小于"<<str2<<endl;
}
else if(strcmp(str1,str2)==0)
{
cout<<str1<<"等于"<<str2<<endl;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值