string 类

要使用string类,必须在程序头文件中#include<string>,string类位于名称空间std中,必须提供一条using编译指令。

         可以使用运算符 + 将两个string对象合并起来,还可以使用运算符 += 将字符串附加到string对象的末尾。

         头文件cstring(以前为string.h)提供字符串的处理函数。

         使用string对象的语法比使用C字符串函数更简单。String类具有自动调整大小的功能。

         intlen1 = str1.seze();

         intlen2 = strlen(charr1);

         函数strlen()是一个常规函数,功能是字符串作为参数,返回字符数。函数size()的功能相同,不同之处是str1不是被用作函数参数,而是位于函数名之前,用句点连接。表明str1是一个string对象,而size()是一个类方法。总之,C函数使用参数来支出要使用哪个字符串,而C++ string类对象使用对象名和句点运算符来指出要使用哪个字符串。

#include <iostream>

#include <string>

#include <cstring>

 

int main()

{

         usingnamespace std;

         charcharr[20];

         stringstr;

 

         cout<< “Length of string in charr before input: ” << strlen(charr)<<endl;

         cout<< “Length of string in str before input: ” << str.size() <<endl;

         cout<< “Enter a line of text:\n”;

         cin.getline(charr,20);

         cout<< “You entered: ” << charr << endl;

         cout<< “Enter another line of text:\n”;

         getline(cin,str);

         cout<< “You entered:” << str << endl;

         cout<< “Length of string in charr after input: ” << strlen(charr)<< endl;

         cout<< “Length of string in str after input: ” << str.size()<<endl;

 

         return0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值