- 3
- 0
- 约6.01千字
- 约 20页
- 2023-04-26 发布于上海
- 举报
字符串操作是一个不小的主题,在标准 C++中,string 字符串类成为一个标准,之所以抛弃char*的字符串而选用 C++标准程序库中的 string 类,是因为他和前者比较起来,不必担心内存是否足够、字符串长度等等,而且作为一个类出现,他集成的操作函数足以完成我们大多数情况下的需要.
下面我们首先从一些示例开始学习下string 类的使用.
1)
#include string #include iostream using namespace std;
void main()
{
string s(hehe);
string s1=abcd; couts” “s1endl;
}
2)
#include string
#include iostream using namespace std;
void main()
{
char chs[] = hehe; string s(chs); coutsendl;
}
3)
#include string #include iostream using namespace std;
void main()
{
char chs[] = hehe;
string s(chs,1,3); //指定从chs 的索引1 开始,最后复制3 个字节coutsendl;
}
4)
#include string #include iostream using namespace std;
void main()
{
string s1(hehe); string s2(s1); couts2endl;
}
5)
#include string #include iostream using namespace std;
void main()
{
string s1(hehe,2,3); string s2(s1); couts2endl;
}
6)
#include string #include iostream using namespace std;
void main()
{
char chs[] = hehe;
string s(chs,3); //将 chs 前 3 个字符作为初值构造coutsendl;
}
7)
#include string #include iostream using namespace std;
void main()
{
string s(10,k); //分配 10 个字符,初值都是k
coutsendl;
}
//以上是 string 类实例的构造手段,都很简单.
9)
// 赋 新 值 #include string
#include iostream using namespace std;
void main()
{
string s(10,k); //分配 10 个字符,初值都是k coutsendl;
s = hehehehe; coutsendl; s.assign(kdje); coutsendl;
s.assign(fkdhfkdfd,5); //重新分配指定字符串的前 5 的元素内
容
coutsendl;
}
10)
//swap 方法交换#include string #include iostream using namespace std;
void main()
{
string s1 = hehe; string s2 = gagaga;
couts1 : s1endl; couts2 : s2endl; s1.swap(s2);
couts1 : s1endl; couts2 : s2endl;
}
11)
//+=,append(),push_back()在尾部添加字符#include string
#include iostream using namespace std;
void main()
{
string s = hehe; s += gaga; coutsendl;
s.append(嘿嘿); //append()方法可以添加字符串coutsendl;
s.push_back(k); //push_back()方法只能添加一个字符... coutsendl;
}
12)
//insert() 插入字符.其实,insert 运用好,与其他的插入操作是一样的. #include string
#include iostream using namespace std;
void main()
{
string s = hehe;
s.insert(0,头部); //在头部插入s.insert(s.size(),尾部); //在尾部插入
s.insert(s.size()/2,中间);//在中间插入c
您可能关注的文档
最近下载
- 精神科暴力行为预防及处置.ppt VIP
- 数列型不等式的放缩方法.docx VIP
- “五个带头”方面存在问题原因剖析、下一步整改措施对照检查材料(六篇)2026年.docx VIP
- 深度解析(2026)《SJT 11140-2022 铝电解电容器用电极箔》.pptx VIP
- RBT 107-2024 能源管理体系 公共建筑管理组织认证要求.pdf VIP
- T_SGZX003—2024固态铝电解电容器用电极箔.pdf VIP
- 2026-2030中国商用飞机铝锂合金行业市场发展趋势与前景展望战略分析研究报告.docx
- 2024年常州信息职业技术学院单招职业技能测试题库(历年真题).docx VIP
- 电气土建工程图例符号.doc VIP
- 新版食品生产许可管理办法.pptx VIP
原创力文档

文档评论(0)