字符串(二):string
字符串使用方法整理 系列:
string 是 C++ STL 的一个字符串类型,原型是 vector<char>
并对字符串处理做了优化。
1. 声明
首先要包括库文件 #include <string>
,这个 <string>
不同于 <cstring>
,是 C++ 专有的库文件。
然后做出声明:
string str;
特殊的,可以赋予 string 初始值:
string a = "text";
string b("text");
string c = a; // 以 string 对 string 赋值也是可以的
2. 访问元素
2.1 直接访问
函数 .length() 可以得到该 string 的长度。
我们可以直接通过元素下标来访问某一个 string 中的字符,如 str[2]
访问第三个字符。
2.2 迭代器
我们也可以使用 vector<char>
相似的函数,如 .size() 是和 .length() 用途相同的函数。
我们也可以使用类似 vector<char>::iterator
的 string::iterator
迭代器来遍历字符串,如:
for (string::iterator i = str.begin(); i != str.end(); i++) {
// do things here
}
注意:同 vector 中的用法一样,通过迭代器遍历 string 时修改 string 的内容长度(如删除 string 中的字符)可能有意想不到的错误。
参考:C++ Reference 官网对 string 类中迭代器函数的定义如下:
begin: Return iterator to beginning (public member function )
end: Return iterator to end (public member function )
rbegin: Return reverse iterator to reverse beginning (public member function )
rend: Return reverse iterator to reverse end (public member function )
cbegin: Return const_iterator to beginning (public member function )
cend: Return const_iterator to end (public member function )
crbegin: Return const_reverse_iterator to reverse beginning (public member function )
crend: Return const_reverse_iterator to reverse end (public member function )
2.3 赋值函数
.assign(...) 赋值函数:
s.assign(str);
s.assign(str, 1, 3); //如果str是"iamangel" 就是把"ama"赋给字符串
s.assign(str, 2, string::npos); //把字符串str从索引值2开始到结尾赋给s
s.assign("gaint");
s.assign("nico", 5); //把’n’ ‘I’ ‘c’ ‘o’ ‘’赋给字符串
s.assign(5, ’x’); //把五个x赋给字符串
3. 操作
3.1 清空 .clear()
用来清空 string。
3.2 判断空 .empty()
返回一个 boolean 值表示 string 是否为空。
3.3 取头部 .front()
返回首字符
3.4 取尾部 .back()
返回尾字符。
3.5 字符串相加
string 重载了 +
符号和 +=
符号,使用方法显而易见。+=
符号与 .append(...) 函数作用相同。如果注重函数式编程,推荐使用 .append(...) 函数。
3.6 插入 .insert(...)
.insert(...) 函数的作用是在字符串某处插入字符(串)。定义如下:
string (1)
string& insert (size_t pos, const string& str);
substring (2)
string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);
c-string (3)
string& insert (size_t pos, const char* s);
buffer (4)
string& insert (size_t pos, const char* s, size_t n);
fill (5)
string& insert (size_t pos, size_t n, char c);
void insert (iterator p, size_t n, char c);
single character (6)
iterator insert (iterator p, char c);
range (7)
template <class InputIterator>
void insert (iterator p, InputIterator first, InputIterator last);
C++ Reference 官网的例子:
// inserting into a string
#include <iostream>
#include <string>
int main ()
{
std::string str="to be question";
std::string str2="the ";
std::string str3="or not to be";
std::string::iterator it;
// used in the same order as described above:
str.insert(6,str2); // to be (the )question
str.insert(6,str3,3,4); // to be (not )the question
str.insert(10,"that is cool",8); // to be not (that is )the question
str.insert(10,"to be "); // to be not (to be )that is the question
str.insert(15,1,':'); // to be not to be(:) that is the question
it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
str.insert (str.end(),3,'.'); // to be, not to be: that is the question(...)
str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
std::cout << str << '\n';
return 0;
}
3.7 删除 .erase(...)
.erase(...) 函数可以删除指定位置的字符(串)。定义如下:
sequence (1)
string& erase (size_t pos = 0, size_t len = npos);
character (2)
iterator erase (iterator p);
range (3)
iterator erase (iterator first, iterator last);
举个例子(来自 C++ Reference):
// string::erase
#include <iostream>
#include <string>
int main ()
{
std::string str ("This is an example sentence.");
std::cout << str << '\n';
// "This is an example sentence."
str.erase (10,8); // ^^^^^^^^
std::cout << str << '\n';
// "This is an sentence."
str.erase (str.begin()+9); // ^
std::cout << str << '\n';
// "This is a sentence."
str.erase (str.begin()+5, str.end()-9); // ^^^^^
std::cout << str << '\n';
// "This sentence."
return 0;
}
3.8 替换 .replace(...)
.replace(...) 函数定义:
string (1)
string& replace (size_t pos, size_t len, const string& str);
string& replace (iterator i1, iterator i2, const string& str);
substring (2)
string& replace (size_t pos, size_t len, const string& str,
size_t subpos, size_t sublen);
c-string (3)
string& replace (size_t pos, size_t len, const char* s);
string& replace (iterator i1, iterator i2, const char* s);
buffer (4)
string& replace (size_t pos, size_t len, const char* s, size_t n);
string& replace (iterator i1, iterator i2, const char* s, size_t n);
fill (5)
string& replace (size_t pos, size_t len, size_t n, char c);
string& replace (iterator i1, iterator i2, size_t n, char c);
range (6)
template <class InputIterator>
string& replace (iterator i1, iterator i2,
InputIterator first, InputIterator last);
举个例子(来自 C++ Reference):
// replacing in a string
#include <iostream>
#include <string>
int main ()
{
std::string base="this is a test string.";
std::string str2="n example";
std::string str3="sample phrase";
std::string str4="useful.";
// replace signatures used in the same order as described above:
// Using positions: 0123456789*123456789*12345
std::string str=base; // "this is a test string."
str.replace(9,5,str2); // "this is an example string." (1)
str.replace(19,6,str3,7,6); // "this is an example phrase." (2)
str.replace(8,10,"just a"); // "this is just a phrase." (3)
str.replace(8,6,"a shorty",7); // "this is a short phrase." (4)
str.replace(22,1,3,'!'); // "this is a short phrase!!!" (5)
// Using iterators: 0123456789*123456789*
str.replace(str.begin(),str.end()-3,str3); // "sample phrase!!!" (1)
str.replace(str.begin(),str.begin()+6,"replace"); // "replace phrase!!!" (3)
str.replace(str.begin()+8,str.begin()+14,"is coolness",7); // "replace is cool!!!" (4)
str.replace(str.begin()+12,str.end()-4,4,'o'); // "replace is cooool!!!" (5)
str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful." (6)
std::cout << str << '\n';
return 0;
}
4. 杂项
4.1 比较
通过 <, >, ==, <=, >=, != 六种比较符号,可以方便地在 string 之间、甚至是在 string 和 c-string 之间进行比较。
.compare(...) 支持多参数处理,支持用索引值和长度定位子串来进行比较。返回一个整数来表示比较结果,返回值意义如下:
0:相等
> 0:大于
< 0:小于
举例如下:
string s("abcd");
s.compare("abcd"); //返回0
s.compare("dcba"); //返回一个小于0的值
s.compare("ab"); //返回大于0的值
s.compare(s); //相等
s.compare(0, 2, s, 2, 2); //用"ab"和"cd"进行比较 小于零
s.compare(1, 2, "bcx", 2); //用"bc"和"bc"比较。
4.2 取子串 .substr(...)
取子串函数 .substr(...):
s.substr(); //返回s的全部内容
s.substr(11); //从索引11往后的子串
s.substr(5, 6); //从索引5开始6个字符
4.3 查找 .find(...)
.find(...) 函数的定义:
string (1)
size_t find (const string& str, size_t pos = 0) const;
c-string (2)
size_t find (const char* s, size_t pos = 0) const;
buffer (3)
size_t find (const char* s, size_t pos, size_t n) const;
character (4)
size_t find (char c, size_t pos = 0) const;
返回值为字符串中第一个匹配的位置;如果没有找到则返回 string::npos
值。
样例(来自 C++ Reference):
// string::find
#include <iostream> // std::cout
#include <string> // std::string
int main ()
{
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
// different member versions of find in the same order as above:
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';
found=str.find("needles are small",found+1,6);
if (found!=std::string::npos)
std::cout << "second 'needle' found at: " << found << '\n';
found=str.find("haystack");
if (found!=std::string::npos)
std::cout << "'haystack' also found at: " << found << '\n';
found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';
// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition");
std::cout << str << '\n';
return 0;
}
4.4 reserve 函数
参见:Link
Further reading:
字符串(二):string的更多相关文章
- 窥探Swift之字符串(String)
之前总结过Objective-C中的字符串<Objective-C精选字符串处理方法>,学习一门新语言怎么能少的了字符串呢.Swift中的String和Objective-C语言中NSSt ...
- 字符串表达式String Expressions
声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...
- JAVA字符串格式化String.format()的使用
JAVA字符串格式化-String.format()的使用常规类型的格式化 String类的format()方法用于创建格式化的字符串以及连接多个字符串对象.熟悉C语言的同学应该记得C语言的sprin ...
- Java:字符串类String的功能介绍
在java中,字符串是一个比较常用的类,因为代码中基本上处理的很多数据都是字符串类型的,因此,掌握字符串类的具体用法显得很重要了. 它的主要功能有如下几种:获取.判断.转换.替换.切割.字串的获取.大 ...
- 前端总结·基础篇·JS(一)五大数据类型之字符串(String)
前端总结系列 前端总结·基础篇·CSS(一)布局 前端总结·基础篇·CSS(二)视觉 前端总结·基础篇·CSS(二)补充 前端总结·基础篇·JS(一)五大数据类型之字符串(String) 目录 这是& ...
- Python基础数据类型-字符串(string)
Python基础数据类型-字符串(string) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 本篇博客使用的是Python3.6版本,以及以后分享的每一篇都是Python3.x版 ...
- JAVA字符串格式化-String.format()的使用 【生成随机数补0操作】
转: JAVA字符串格式化-String.format()的使用 常规类型的格式化 String类的format()方法用于创建格式化的字符串以及连接多个字符串对象.熟悉C语言的同学应该记得C语言的s ...
- Java基础-字符串(String)常用方法
Java基础-字符串(String)常用方法 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.java的API概念 Java的API(API:Application(应用) Pr ...
- Kotlin——初级篇(八):关于字符串(String)常用操作汇总
在前面讲解Kotlin数据类型的时候,提到了字符串类型,当然关于其定义在前面的章节中已经讲解过了.对Kotlin中的数据类型不清楚的同学.请参考Kotlin--初级篇(三):数据类型详解这篇文章. 在 ...
- 前端总结·基础篇·JS(一)原型、原型链、构造函数和字符串(String)
前端总结系列 前端总结·基础篇·CSS(一)布局 前端总结·基础篇·CSS(二)视觉 前端总结·基础篇·CSS(三)补充 前端总结·基础篇·JS(一)原型.原型链.构造函数和字符串(String) 前 ...
随机推荐
- try...catch语句
程序的异常:Throwable 严重问题Error我们不处理,这种问题一般都是很严重的,比如内存溢出 问题Exception 编译期问题不是RuntimeException的异常必须进行处理,如果不处 ...
- 双系统(win10+ubuntu)卸载Ubuntu系统
之前装的双系统,Win10 和Ubuntu ,系统引导使用的是Ubuntu的Grup的引导, 直接删除Ubuntu会导致引导丢失,会很麻烦,win10直接会挂掉,后期恢复需要重建引导 安全删除思路,先 ...
- js-用判断音乐或图片是否加载完成的方式来控制页面的现实
判断页面加载,加完完成后,内容页显示,加载条隐藏 百度搜索方法很多,大多都是: document.onreadystatechange = function() //当页面加载状态改变的时候执行fun ...
- 结合element-ui封装的一个分页函数
第一次写博客,专门写给菜鸟看的,如果你是老鸟,你可以直接无视. 首先我们从豆瓣api获取到电影的数据列表 然后我们把他们切成一块一块的小数组 最后的数组将会是这样 原理就是以上的内容,接下来直接附上 ...
- [Web 前端] 019 css 定位之绝对定位与相对定位
1. 关于定位 我们可以使用 css 的 position 属性来设置元素的定位类型 postion 的设置项如下 设置项 释义 relative 生成相对定位元素元素所占据的文档流的位置不变元素本身 ...
- [Markdown] 04 进阶语法 第二弹
[TOC] 接上一篇 [Mardkown] 03 进阶语法 第一弹 8. LaTeX 8.1 相关介绍 TeX:学术排版 LaTeX:相当于 TeX 的简化版本:对公式编辑精细至像素级别 MathJa ...
- 如何使用IDEA将项目上传到GitHub中
上传之前先规定上传的格式: 1 . 以后所有上传的项目,都只上传 src文件集以及pom.xml文件,不要带有自己的 .idea配置文件或者target运行文件之类的(就算是测试文件也一样,从开始就养 ...
- dfs(首尾字母)
http://acm.hdu.edu.cn/showproblem.php?pid=1181 变形课 Time Limit: 2000/1000 MS (Java/Others) Memory ...
- 三大浏览器(火狐-谷歌-IE浏览器)驱动版本下载
1.chrome浏览器: 对于chrome浏览器,有时候会有闪退的情况,有时候也许是版本冲突的问题,我们要对照着这个表来对照查看是不是webdriver和chrome版本不对应 点击下载chrome的 ...
- 利用js使图片外层盒子的高等于适应图片的高
JS代码如下:<script> $(window).load(function(){ var width=$(window).width(); var img_1=$(".hot ...