字符串(二):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) 前 ...
随机推荐
- .net任务调度平台 Dyd.BaseService.TaskManager
国外网速慢,最新版本迁移至http://git.oschina.net/chejiangyi/Dyd.BaseService.TaskManager .net 简单任务调度平台 用于.net dll, ...
- C#—Nhibernate使用教程
本篇文章,让我们一起来探索Nhibernate.首先我们去搜索Nhibernate下载地址,如下链接所示.该版本可能是最新版,我下载的4.0.4.GA.其中GA意思我没搞清楚.不过应该不重要.http ...
- Http中Content-Type的取值讲解
一.Content-Type的取值 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息(MediaType,即是Internet Media Type,互联网媒体类型: ...
- Java判断一个类里是否存在某个属性
Java判断一个类里是否存在某个属性 测试pojo类,比方我有个User类 @Getter @Setter public class User { private Long id; private S ...
- ubuntu终端代理之proxychains
命令行代理 安装proxychains sudo apt install proxychains 配置proxychains sudo vim /etc/proxychains.conf 在proxy ...
- HDU 6631 line symmetric(枚举)
首先能想到的是至少有一对相邻点或者中间间隔一个点的点对满足轴对称,那么接下来只需要枚举剩下的点对是否满足至多移动一个点可以满足要求. 第一种情况,对于所有点对都满足要求,那么Yes. 第二种情况,有一 ...
- Appium+Python之测试数据与脚本分离
如果脚本中有很多的魔法数据,那代码的复用性就不会很高,所以我们需要将测试数据和脚本分离. 思路:将测试数据放在一个json文件中,然后写一个读取json文件的基类,测试用例中通过调基类中方法来获取js ...
- Vue-cli2项目文件目录解析
前言 不是原创,真的不是原创,主要我是根据CSDN的一篇文章和其他平台上的文章整理而来,在最后我会贴上所有原文的地址,下面正式进入正文. Vue-cli项目文件目录结构 这个是Vue-cli2.0版本 ...
- 【vue】父子组件间通信----传函数
(一)子组件 调用 父组件 方法 方式一) 子组件中通过this.$parent.event来调用父组件的方法 父组件 <template> <div> <child&g ...
- “没有找到mfc100u.dll”的解决方法
现在需要安装 MindManager 2016 思维导图软件时,打开软件提示找不到 mfc100u.dll,无法执行程序.之前一直好好的,现在换电脑了安装提示这个问题,然后百度找的解决方案: 需要去微 ...