
学习笔记:string类
发布日期:2021-05-14 16:30:21
浏览次数:14
分类:精选文章
本文共 1246 字,大约阅读时间需要 4 分钟。
前言
郭炜老师视频笔记一、string类
错误的初始化方法:
string error1 = ‘c’;
string error2 = (‘u’);
string error3 = 22;
string error4(8);
可以将字符串赋值给string对象:
string s1;
s = ‘n’;
string month = “month”;
string s2(8, ‘x’);
// 输出为:xxxxxxxxstring s3 = “hello”;
二、string成员函数
string对象的长度用成员函数length()
获取:
string s("hello");cout << s.length();
string支持流读取运算符:
string stringObject;cin >> stringObject;
string支持getline()
函数:
string s;getline(cin, s);
比较大小compare
:
string s1("hello"), s2("hello"), s3("hell");int f1 = s1.compare(s2); // 0int f2 = s1.compare(s3); // 1int f3 = s3.compare(s1); // -1int f4 = s1.compare(1, 2, s3, 0, 3); // 1int f5 = s1.compare(0, s1.size(), s3); // 0
输出结果:
0 1 -1 -1 1成员函数substr
:
string s1("hello world"), s2;s2 = s1.substr(4, 5); // 输出:world
寻找string中的字符:
string s1("hello worlld");s1.find("ll", 1); // 2s1.find("ll", 2); // 2s1.find("ll", 3); // 9
成员函数find_first_of()
等:
string s1("hello world");s1.find_first_of("abcd"); // 2 (d)
删除erase()
:
string s1("hello world");s1.erase(5); // 输出:hell
替换replace()
,插入insert()
:
string s1.replace(4, 5, "wor"); // 替换子串 string s2.insert(2, "World"); // 插入World在位置2
转换成C语言式char*
字符串:
string s1("hello world");cout << s1.c_str(); // 输出:hello world
总结
当要使用String库的时候,直接搜......发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月07日 19时46分58秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
单选框点击文字也能选中
2019-03-11
此主机支持Intel VT-x,但Intel VT-x 处于禁用状态。
2019-03-11
06-局部变量和全局变量
2019-03-11
12-面向对象1
2019-03-11
python基础总结 异常处理
2019-03-11
解决Vue源码运行错误
2019-03-11
HDU - 4109 Instrction Arrangement
2019-03-11
Lua websocket长连接
2019-03-11
SQL 分页查询 返回总条数
2019-03-11
重写的特点
2019-03-11
计算机网络UDP协议和TCP协议
2019-03-11
Linux运行C语言文件
2019-03-11
C字符串高级
2019-03-11
2010-03-25 函数题
2019-03-11
C语言_动态内存分配练习
2019-03-11
Linux学习_系统进程概念
2019-03-11
七层网络模型(待添加)
2019-03-11
考研复试——KY276 Problem C
2019-03-11
老鸟带你画tiled lines
2019-03-11
MybatisPlus自定义Sql实现多表查询
2019-03-12