【C++练习系列】字符数组的函数,你会用吗?

(1)cin.getline( )函数

一般来说,输入字符串时,遇到空格或者回车键,系统会认为字符串结束。
cin.getline( )函数可以实现输入包含空格的字符串到字符数组中去。

表达式:cin.getline( char *a , int size , char=‘\n’)
(括号里面第一个参数代表:一维字符数组;第二个参数代表:读取的最大字符个数,第三个参数代表:分界界限的字符,默认是:\n,及换行符。)

其中,cin.getline(a,80,‘?’):表示输入?号,结束。

#include <iostream>
using namespace std;
int main()
{
    char a[80];
    cin.getline(a, 80);    //默认\n结束
    cout << a << endl;
    return 0;
}

(2)strcpy( )函数、strncpy( )函数

strcpy( )函数:将第二个数组的字符串复制到第一个数组中去;
strncpy( )函数:将第二个数组前n个字符复制到第一个数组中去。

函数要有头文件:#include <string.h>
字符数组要留一个空间放: \0

#include <iostream>
using namespace std;
#include <string.h>
int main()
{
    char a1[10] = "haidanubi";
    char b1[10], b2[6];
    strcpy(b1, a1);
    cout << b1 << endl;   //答案:haidanubi

    strncpy(b2, a1, 5);
    cout << b2 << endl;   //答案:haida
    return 0;
}

(3)strcmp( )函数、strncmp( )函数

strcmp( )函数:比较两个字符串数组的大小。
字符串1等于字符串2,输出为:0;
字符串1大于字符串2,输出为:1;
字符串1小于字符串2,输出为:-1;

strncmp( )函数:比较两个字符串数组前n个字符串的大小。

函数要有头文件:#include <string.h>

#include <iostream>
using namespace std;
#include <string.h>
int main()
{
    char a[2][20] = {"aaabnuibi", "aaaa"};
    
    cout << strcmp(a[0], a[0]) << endl;       //0
    cout << strcmp(a[0], a[1]) << endl;       //1
    cout << strncmp(a[0], a[1], 3) << endl;   //0
    cout << strncmp(a[0], a[1], 4) << endl;   //1
    return 0;
}

(4)strlen( )函数

strlen( )函数:计算字符数组中有效字符的个数,不包括’\0’

函数要有头文件:#include <string.h>
答案是10,而不是11!

#include <iostream>
using namespace std;
#include <string.h>
int main()
{
    cout << strlen("haidanuibi");
    return 0;
}

(5)strcat( )函数

strcat( )函数:将第二个数组的字符串连接到第一个字符数组中。

函数要有头文件:#include <string.h>

#include <iostream>
using namespace std;
#include <string.h>
int main()
{
    char a[10] = "haida";
    char b[10] = "nuibi";
    strcat(a, b);
    cout << a << endl;
    return 0;
}

(6)strlwr( )函数、strupr( )函数

strlwr( )函数:能将大写字母转换为小写字母;
strupr( )函数:能将小写字母转换为大写字母;

函数要有头文件:#include <string.h>

#include <iostream>
using namespace std;
#include <string.h>
int main()
{
    char a[20] = "HaiDaNuiBi";
    strlwr(a);
    cout << a << endl;
    strupr(a);
    cout << a << endl;
    return 0;
}

最后我想说的是,这是我的【C++练习系列】的第五篇文章,主要介绍了字符数组的一些常用函数。如果喜欢的话,多多点赞。也希望能看看前面的四篇文章!

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

在下_诸葛

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

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

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

打赏作者

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

抵扣说明:

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

余额充值