基于c++浅谈string类函数

本文通过C++代码示例详细介绍了字符串的各种操作方法,包括初始化、连接、比较、查找等,并展示了如何使用长度、容量等属性进行字符串管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string>
using namespace std;
int main()
{
 string str1(5, 'c');
 string str2("Now is the time ...");
 string str3(str2, 11, 4);
 string str4("hello world", 6);
 cout << str1 << endl;
 cout << str2 << endl;
 cout << str3 << endl;
 cout << str4 << endl;
 string str5 = str1 + str2;
 cout << str5 << endl;
 cout << "下面开始字符串比较" << endl;
 cout << (str1 == str2) << endl;
 cout << (str1 != str2) << endl;
 cout << (str1 > str2) << endl;
 cout << (str1 < str2) << endl;
 cout << str1[3] << endl;
 cout << "其他方法调用" << endl;
 cout << str1.length() <<endl;                    //string类型求长度
 cout << (str2.find('1') == string::npos) << endl;       //寻找字符串中是否有某个字符
 cout << str2.at(3) << endl;        //取其中的第4个元素
 cout << str2.length() << "," << str2.capacity() << endl;
 string first("This comes first");
 string second("And this is second");
 first.swap(second);
 cout << first << endl;
 cout << second << endl;
 cout << str4.rfind("hello") << endl;
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值