一、字符串及区别
(1)字符串
字符串是表示字符序列的对象。标准字符串类(string)通过类似于标准字节容器的接口为这些对象提供支持,但添加了专门设计用于使用单字节字符串操作的功能。
该字符串类(string)是一个实例的basic_string类模板使用字符(即字节)作为其类型,其默认char_traits和分配器类型(见basic_string的更多信息的模板)。
请注意,此类(string)独立于所使用的编码处理字节:如果用于处理多字节或可变长度字符(如UTF-8)的序列,此类的所有成员(如长度或大小),以及它的迭代器仍将以字节(不是实际编码字符)的形式运行。
(2)区别
#include <string> , #include <cstring>, #include <string.h>区别。
①#include <string>是 C++中新添加的类库。(如求字符串大小可以用 str.size();)
②#include <string.h>是 C 中的标准类库。 (如求字符串大小可以用 strlen(str);)
③C++ 为了支持 C,同时为了区别 C,所以对 C 标准类库做了一些更改,将 C 类库中的尾缀 .h 去掉 ,添加首字母 c。所以在 C++ 中 #include <cstring>, #include <string.h> 是等同的,代表同一个类库,只不过名称有所区别。 (如求字符串大小可以用 strlen(str);)
二、函数总览
1.迭代器
begin | 返回字符串开头的迭代器 |
end | 返回字符串末尾的理论迭代器,此不应该被引用。因为标准库的函数使用的范围不包括其关闭迭代器指向的元素。 |
rbegin | 字符串反向开头的反向迭代器 |
rend | 返回一个反向迭代器,指向字符串第一个字符前面的理论元素(被认为是它的反向结束) |
2.容量
size / length | 返回字符串长度,返回类型 size_t (unsigned int 类型)和 string::size_type同一类型 |
clear | 清空字符串,返回类型 void |
empty | 判断字符串是否为空,返回类型 void |
注:max_size; resize; capacity; reserve; 这几个不常用,再此不列举,如想了解详情可以参看博主的另一篇vector文章 https://blog.youkuaiyun.com/qq_41291253/article/details/89840185。
3.元素访问
operator[] | 获取指定位置的字符,返回类型 char& |
at | 获取指定位置的字符,返回类型 char& |
4.编辑器
operator+= | 通过在当前字符串末尾添加其他字符来扩充字符串 返回string& |
push_back | 将单个字符添加字符串末尾,使其长度加1 返回 void |
assign | 为字符串分配一个新值,替换其当前内容(先清空在复制) 返回string& |
insert | 在pos(或p)指示的字符前面位置插入其他字符 返回string&,如果返回为迭代器类型,则返回插入的第一个字符的迭代器 |
erase | 删除部分字符串,减少其长度 返回string &,如果返回为迭代器类型,则返回现在占据删除第一个位置的字符,如果不存在这样的字符则返回 string::end()。 |
replace | 用新的字符串替换以pos字符开头长度为 len的字符串,(或[i1,i2)之间的范围内的字符串部分) 返回string & |
swap | 用str的内容交换容器的内容,str是另一个字符串对象。长度可能不同。在调用此成员函数之后,此对象的值是调用之前str的值,str的值是此对象在调用之前具有的值 返回 void |
pop_back | 删除最后一个字符删除字符串的最后一个字符,有效地将其长度减少1 返回 void |
append | 通过在其当前值的末尾附加其他字符来扩展字符串 |
5.字符串操作
copy | 将当前字符串对的子字符串复制到s指向的数组中。此子字符串包含从位置pos开始的len个字符。 该函数不会在复制内容的末尾附加空字符。 返回:复制到s指向的数组的字符数。这可能等于len或length()- pos(如果字符串值小于pos + len) |
find | 在字符串中搜索由其参数指定的第一个匹配项的序列(所有字符按顺序完全匹配)。 返回:完全匹配后,第一次匹配的第一个字符的位置。如果未找到匹配项,则函数返回string :: npos |
rfind | 在字符串中搜索由其参数指定的最后一次出现的序列(所有字符按顺序完全匹配)。 返回:完全匹配后,最后一次匹配的第一个字符的位置。如果未找到匹配项,则函数返回string :: npos |
find_fist_of | 在字符串中搜索与其参数中指定的任何字符(随意一个就可以,无先后顺序,也不用完全匹配)匹配的第一个字符。 返回:第一次匹配的第一个字符的位置。如果未找到匹配项,则函数返回string :: npos。 |
find_last_of | 在字符串中搜索与其参数中指定的任何字符匹配的最后一个字符。 返回:匹配的最后一个字符的位置。如果未找到匹配项,则函数返回string :: npos。 |
find_fist_not_of | 在字符串中搜索与其参数中指定的任何字符都不匹配的第一个字符(找不同)。 返回:第一次匹配的第一个字符的位置。如果未找到匹配项,则函数返回string :: npos。 |
find_last_not_of | 在字符串搜索与其参数中指定的任何字符都不匹配的最后一个字符。 返回:匹配的最后一个字符的位置。如果未找到匹配项,则函数返回string :: npos。 |
substr | 返回一个新构造的字符串对象,其值初始化为此对象的子字符串的副本。 |
compare | 将字符串对象(或子字符串)的值与其参数指定的字符序列进行比较。 |
6.非成员函数重载
getline | 从输入流中获取一行字符到回车符终止获取,空格也获取 |
7.成员常数
npos | size_t 的最大值 |
读者想查看哪一步分内容直接点击下面相应链接即可。
目录
size / length:--->clear:--->empty:
operator+=:--->push_back:--->assign:--->insert:--->erase:--->replace:--->swap:--->pop_back: --->append
copy:--->find:---> rfind:---> find_fist_of:--->find_last_of--->find_fist_not_of:--->find_last_not_of:--->substr:--->compare:
三、函数详解
1.迭代器
rebegin:
返回字符串反向开头的“反向迭代器”。
reverse_iterator rbegin();
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::rbegin
函数输入:void
函数输出:反向后开头的反向迭代器reverse_iterator
=============================================*/
int main()
{
string str("now step live...");
//for(string::reverse_iterator rit = str.rbegin(); rit != str.rend(); rit++)
//如果为 begin 则 for(string::iterator it = str.begin(); it != str.end(); it++)
for(string::reverse_iterator rit = str.rbegin(); rit <= str.rend(); rit++)
cout << *rit;
cout << endl;
return 0;
}
/*===============================================
函数输出:...evil pets won
===============================================*/
2.容量
size / length:
返回字符串的长度,从 1 开始计数
size_t size()const; //size_t 为 unsigned int 类型
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::size
函数输入:void
函数输出:字符串中的字节数,size_t类型
=============================================*/
int main()
{
string str("Test string");
cout << "The size of str is " << str.size() << " bytes." << endl;
cout << "The length of str is " << str.length() << " bytes." << endl;
return 0;
}
/*===============================================
函数输出:The size of str is 11 bytes.
The length of str is11 bytes.
===============================================*/
clear:
清空字符串
void clear();
函数用例
/*==============================================
函数名称:std::string::clear
函数输入:void
函数输出:void
=============================================*/
int main()
{
char c;
std::string str;
std::cout << "Please type some lines of text. Enter a dot (.) to finish:\n";
do {
c = cin.get(); //输入单个字符
str += c; //将字符加入到Str尾部,见下文
if (c == '\n')
{
cout << str;
str.clear();
}
} while (c != '.'); //判断语句为真,继续循环
return 0;
}
/*===============================================
函数输出:Please type some lines of text. Enter a dot (.) to finish:
I am a student
I am a student
I am a student.
===============================================*/
empty:
判断字符串是否为空
bool empty()const;
函数用例
/*==============================================
函数名称:std::string::empty
函数输入:void
函数输出:1 - 字符串为空
0 - 字符串非空
函数功能:该程序逐行读取用户输入并将其存储到字符串内容中,直到输入空行。
=============================================*/
int main()
{
string content;
string line;
cout << "Please introduce a text. Enter an empty line to finish: " << endl;
do{
getline(cin, line);
content += line + '\n';
}while(!line.empty());
cout << "The text you introduced was:\n" << content;
return 0;
}
/*===============================================
函数输出:Please introduce a text. Enter an empty line to finish:
I am a student
I am a man
The text you introduced was:
I am a student
I am a man
===============================================*/
3.元素访问
获取字符串中指定位置元素
char&operator [](size_t pos);
char&at(size_t pos);
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::operator[]
函数输入:POS - 字符串的指定位置
注意:字符串中的第一个字符是值 0 (不是 1 )。
函数输出:字符串中指定位置的元素
注:at()相对于 operator[]多出的功能:at()函数自动检查pos是否是字符串中字符的有效位置
(即,pos是否小于字符串长度),如果不是则抛出out_of_range异常。
=============================================*/
int main()
{
string str("Test string");
for(int i = 0; i < str.size(); i++)
cout << str[i];
cout << endl;
string str2 = "Test string 2";
for(int i = 0; i < str2.length(); i++)
cout << str2.at(i);
cout << endl;
return 0;
}
/*===============================================
函数输出:Test string
Test string 2
===============================================*/
4.编辑器
operator+=:
通过在当前字符串末尾添加其他字符来扩充字符串
string (1) | |
---|---|
c-string (2) | |
character (3) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::operator+=
函数输入:str - 一个字符串对象,将其值复制到当前字符串末尾(string)
s - 指向以null 结尾的字符序列的指针,将序列复制到字符串末尾(c-string)
c - 一个字符,附加到当前字符串末尾(character)
函数输出:1 - 字符串为空
0 - 字符串非空
函数功能:该程序逐行读取用户输入并将其存储到字符串内容中,直到输入空行。
=============================================*/
int main()
{
string name("John");
string family("Smith");
name += " K. "; //c-string
name += family; //string
name += '\n'; //character
cout << name;
return 0;
}
/*===============================================
函数输出:John K. Smith
===============================================*/
注:想了解更多可以参考 append ,直接点击即可进入链接。
push_back:
将单个字符添加字符串末尾,使其长度加1
void push_back(char c);
函数用例
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
/*==============================================
函数名称:std::string::push_back
函数输入:c - 一个字符,附加到当前字符串末尾(character)
函数输出:void
=============================================*/
int main()
{
string str;
ifstream file("text.txt", ios::in);
if(file)
while(!file.eof())
str.push_back(file.get());
cout << str << endl;
return 0;
}
/*===============================================
此示例逐个字符地读取整个文件,使用push_back将每个字符附加到字符串对象。
===============================================*/
assign:
为字符串分配一个新值,替换其当前内容
string (1) | |
---|---|
substring (2) | |
c-string (3) | |
buffer (4) | |
fill (5) | |
range (6) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::assign
函数输入:str - 另一个字符串对象,其值可以复制或移动
substr - str中子串的第一个字符的位置,作为子字符串复制到对象。
如果这大于str的长度,它会抛出out_of_range。
注意:str中的第一个字符用值0表示(不是1)。
sublen - 要复制的子字符串的长度(如果字符串较短,则复制尽可能多的字符)
s - 指向字符数字的指针
n - 要复制的字符数
c - 字符值,重复n 次
fist,last - 将迭代器输入到范围中的初始位置和最终位置。
使用的范围为[first, last)
函数模板参数InputIterator应该是一个输入迭代器类型,它指向可转换为char的类型的元素。
如果InputIterator是一个整数类型,则参数将转换为正确的类型,以便使用signature(5)
size_t是无符号整数类型
函数输出:string &
=============================================*/
int main()
{
std::string str;
std::string base="The quick brown fox jumps over a lazy dog.";
// used in the same order as described above:
str.assign(base);
std::cout << str << '\n';
str.assign(base,10,9);
std::cout << str << '\n'; // "brown fox"
str.assign("pangrams are cool",7);
std::cout << str << '\n'; // "pangram"
str.assign("c-string");
std::cout << str << '\n'; // "c-string"
str.assign(10,'*');
std::cout << str << '\n'; // "**********"
str.assign(base.begin()+16,base.end()-12);
std::cout << str << '\n'; // "fox jumps over"
return 0;
}
/*===============================================
函数输出:The quick brown fox jumps over a lazy dog.
brown fox
pangram
c-string
**********
fox jumps over
===============================================*/
insert:
在pos(或p)指示的字符前面位置中插入其他字符:
string (1) | |
---|---|
substring (2) | |
c-string (3) | |
buffer (4) | |
fill (5) | |
single character (6) | |
range (7) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::insert
函数输入:pos - 插入点:新元素插入位置为 pos 处的字符之前
如果插入值大于对象长度,则抛出 out_of_range
注意:第一个字符由值 0 表示
str - 另一个字符串对象,其值可以复制或移动
substr - str中子串的第一个字符的位置,作为子字符串复制到对象。
如果这大于str的长度,它会抛出out_of_range。
注意:str中的第一个字符用值0表示(不是1)。
sublen - 要复制的子字符串的长度,即复制字符个数,从 1 开始
s - 指向字符数组的指针
n - 要复制的字符数
c - 字符值,重复n 次
p - 指向插入点的迭代器:在 p 指向的字符之前插入新内容。
iterator是一个成员类型,定义为指向字符串字符的随机访问迭代器类型。
fist,last - 将迭代器输入到范围中的初始位置和最终位置。
使用的范围为[first, last)
函数模板参数InputIterator应该是一个输入迭代器类型,它指向可转换为char的类型的元素。
如果InputIterator是一个整数类型,则参数将转换为正确的类型,以便使用signature(5)
size_t是无符号整数类型
函数输出:string &
如果返回为迭代器类型,则返回插入的第一个字符的迭代器。
=============================================*/
int main()
{
string str = "to be question";
string str2 = "the ";
string str3 = "or not to be";
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 thequestion
it = str.insert(str.begin() + 5, ','); //to be(,) not to be: that is the question
cout << *it <<endl;
str.insert(str.end(), 3, '.'); //to be, not to be: that is the question(...)
//此处虽然定义中的返回值为 void ,但是在实际写程序时还是可以看出是有返回值的,且返回值为iterator 类型,为插入的第一个字符的迭代器
it = str.insert(it + 2, str3.begin(), str3.begin() + 3); //(or)
cout << *it <<endl;
cout << str <<endl;
return 0;
}
/*===============================================
函数输出:,
o
to be, or not to be: that is the question...
===============================================*/
erase:
删除部分字符串,减少其长度
sequence (1) | |
---|---|
character (2) | |
range (3) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::erase
函数输入:pos - 删除点:要删除的第一个字符的位置
如果其值大于对象长度,则抛出 out_of_range
注意:第一个字符由值 0 表示
len - 要删除的字符数,即删除字符个数,从 1 开始,如果为默认值则删除到结尾
p - 要删除字符的迭代器
fist,last - 迭代器指定要删除的字符串中的范围:[first,last)
size_t是无符号整数类型
函数输出:string &
如果返回为迭代器类型,则返回现在占据删除第一个位置的字符,如果不存在这样的字符则返回 string::end()。
=============================================*/
int main()
{
string str = "This is an example sentence.";
cout << str <<endl;
str.erase(10, 8);
cout << str << endl;
str.erase(str.begin() + 9);
cout << str << endl;
str.erase(str.begin() + 5, str.end() - 9);
cout << str <<endl;
return 0;
}
/*===============================================
函数输出:This is an example sentence.
This is an sentence.
This is a sentence.
This sentence.
===============================================*/
replace:
用新的字符串替换以pos字符开头长度为 len的字符串,(或[i1,i2)之间的范围内的字符串部分)
string (1) | |
---|---|
substring (2) | |
c-string (3) | |
buffer (4) | |
fill (5) | |
range (6) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::replace
函数输入:str - 另一个字符串对象,其值可以复制或移动
pos - 替换点:要替换的第一个字符的位置
如果这大于对象长度,则抛出 out_of_range
注意:第一个字符由值 0 表示
len - 原字符串要替换的字符数,从 pos 点开始,pos 点为 1 字符
subpos - str中子串的第一个字符的位置,复制到对象作为替换。
如果这大于str的长度,它会抛出out_of_range。
注意:str中的第一个字符用值0表示(不是1)。
s - 指向字符数组的指针
n - 要复制的字符数
c - 字符值,重复n 次
fist,last - 将迭代器输入到范围中的初始位置和最终位置。
使用的范围为[first, last)
函数输出:string &
=============================================*/
int main()
{
string base="this is a test string.";
string str2="n example";
string str3="sample phrase";
string str4="useful.";
// replace signatures used in the same order as described above:
// Using positions: 0123456789*123456789*12345
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)
cout << str << '\n';
return 0;
}
/*===============================================
函数输出:replace is useful.
===============================================*/
swap:
用str的内容交换容器的内容,str是另一个字符串对象。长度可能不同。在调用此成员函数之后,此对象的值是调用之前str的值,str的值是此对象在调用之前具有的值。
void swap(string&str);
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::swap
函数输入:str - 另一个字符串对象,其值可以复制或移动
函数输出:void
=============================================*/
int main()
{
string buyer("money");
string seller("goods");
cout << " Before the swap, buyer has " << buyer;
cout << " and seller has " << seller << endl;
seller.swap(buyer);
cout << " After the swap, buyer has " << buyer;
cout << " and seller has " << seller << endl;
return 0;
}
/*===============================================
函数输出: Before the swap, buyer has money and seller has goods
After the swap, buyer has goods and seller has money
===============================================*/
pop_back:
删除最后一个字符删除字符串的最后一个字符,有效地将其长度减少一个。
void pop_back();
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::pop_back
函数输入:void
函数输出:void
=============================================*/
int main()
{
std::string str ("hello world!");
str.pop_back();
std::cout << str << '\n';
return 0;
}
/*===============================================
函数输出:hello world
===============================================*/
append:
通过在其当前值的末尾附加其他字符来扩展字符串:
string (1) | string& append (const string& str); |
---|---|
substring (2) | string& append (const string& str, size_t subpos, size_t sublen); |
c-string (3) | string& append (const char* s); |
buffer (4) | string& append (const char* s, size_t n); |
fill (5) | string& append (size_t n, char c); |
range (6) | template <class InputIterator> string& append (InputIterator first, InputIterator last); |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::append
函数输入:str - 另一个字符串对象,其值被追加。
subpos - str中第一个字符的位置,作为子字符串复制到对象。
如果这大于str的长度,它会抛出out_of_range。
注意:str中的第一个字符用值0表示(不是1)。
sublen - 要复制的子字符串的长度(如果字符串较短,则复制尽可能多的字符)。
string :: npos的值表示直到str结尾的所有字符。
s - 指向字符数组(例如c字符串)的指针。
n - 要复制的字符数。
c - 字符值,重复n次。
first, last - 将迭代器输入到范围中的初始位置和最终位置。
使用的范围为[第一,最后一个),其中包括所有之间的字符第一和最后一个,
包括由指向的字符第一但不被指向的字符最后。
函数输出:字符串的引用
=============================================*/
// appending to string
#include <iostream>
#include <string>
int main ()
{
std::string str;
std::string str2="Writing ";
std::string str3="print 10 and then 5 more";
// used in the same order as described above:
str.append(str2); // "Writing "
str.append(str3,6,3); // "10 "
str.append("dots are cool",5); // "dots "
str.append("here: "); // "here: "
str.append(10u,'.'); // ".........."
str.append(str3.begin()+8,str3.end()); // " and then 5 more"
str.append<int>(5,0x2E); // "....."
std::cout << str << '\n';
return 0;
}
/*===============================================
函数输出:Writing 10 dots here: .......... and then 5 more.....
===============================================*/
5.字符串操作
copy:
将当前字符串对的子字符串复制到s指向的数组中。此子字符串包含从位置pos开始的len个字符。 该函数不会在复制内容的末尾附加空字符。
size_t copy(char * s,size_t len,size_t pos = 0)const;
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::copy
函数输入:s - 指向数组的指针
该数组应该包含足够的存储空间用于存储复制的字符
len - 要复制的字符数
pos - 要复制的第一个字符的位置
函数输出:复制到s指向的数组的字符数。
这可能等于len或length()- pos(如果字符串值小于pos + len)。
=============================================*/
int main()
{
char buffer[20];
string str ("Test string...");
size_t length = str.copy(buffer,6,5);
buffer[length]='\0';
cout << "buffer contains: " << buffer << '\n';
return 0;
}
/*===============================================
函数输出:buffer contains: string
===============================================*/
find:
在字符串中查找内容
在字符串中搜索由其参数指定的第一个匹配项的序列(所有字符按顺序完全匹配)。
当指定pos时,搜索仅包括位置pos处或之后的字符,忽略包括pos之前的字符的任何可能的出现。
请注意,与成员find_fist_of不同,每当搜索多个字符时,仅仅其中一个字符匹配是不够的,但整个序列必须匹配
string (1) | |
---|---|
c-string (2) | |
buffer (3) | |
character (4) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::find
函数输入:str - 要搜索的子字符串
pos - 被搜索的主串中指定搜索开始的第一个字符的位置
如果这大于字符串长度,则函数永远不会找到匹配项。
注意:第一个字符由值0(不是1)表示:值为0表示搜索整个字符串。
s - 指向一组字符的指针
如果指定了参数n,则要匹配的序列是数组中的前n个字符。
否则,期望以空终止的序列:要匹配的序列的长度由第一次出现的空字符确定。
n - 要匹配的字符序列的长度
c - 要搜索的字符
函数输出:完全匹配后,第一次匹配的第一个字符的位置
如果未找到匹配项,则函数返回string :: npos。
size_t 是无符号整形
=============================================*/
int main()
{
string str ("There are two needles in this haystack with needles.");
string str2 ("needle");
// different member versions of find in the same order as above:
size_t found = str.find(str2);
if (found != string::npos) //npos 表示无匹配项
cout << "first 'needle' found at: " << found << '\n';
found = str.find("needles are small", found + 1, 6); //从第 15 位开始搜索
if (found != string::npos)
cout << "second 'needle' found at: " << found << '\n';
found = str.find("haystack");
if (found != string::npos)
cout << "'haystack' also found at: " << found << '\n';
found = str.find('.');
if (found != string::npos)
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;
}
/*===============================================
函数输出:first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.
===============================================*/
rfind:
在字符串中查找最后出现的内容
在字符串中搜索由其参数指定的最后一个匹配项的序列(所有字符按顺序完全匹配)。
当指定pos时,搜索仅包括在位置pos处或之前开始的字符序列,忽略在pos之后开始的任何可能的匹配。
string (1) | |
---|---|
c-string (2) | |
buffer (3) | |
character (4) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::rfind
函数输入:str - 要搜索的子字符串
pos - 主串中要搜索的最后一个字符的位置,即搜索之前的字符
如果这大于字符串长度,则函数永远不会找到匹配项。
注意:第一个字符由值0(不是1)表示:值为s.size()- 1表示搜索整个字符串。
s - 指向一组字符的指针
如果指定了参数n,则要匹配的序列是数组中的前n个字符。
否则,期望以空终止的序列:要匹配的序列的长度由第一次出现的空字符确定。
n - 要匹配的字符序列的长度
c - 要搜索的字符
函数输出:完全匹配后,最后一次匹配的第一个字符的位置
如果未找到匹配项,则函数返回string :: npos。
size_t 是无符号整形
=============================================*/
int main()
{
std::string str ("The sixth sick sheik's sixth sheep's sick.");
std::string key ("sixth");
std::size_t found = str.rfind(key, 9);
if (found!=std::string::npos)
str.replace (found,key.length(),"seventh");
std::cout << str << '\n';
return 0;
}
/*===============================================
函数输出:The seventh sick sheik's sixth sheep's sick.
===============================================*/
find_fist_of:
在字符串中查找字符
在字符串中搜索与其参数中指定的任何字符匹配的第一个字符。
当指定pos时,搜索仅包括位置pos处或之后的字符,忽略pos之前可能出现的任何事件。
请注意,序列的一个单个字符匹配(不是全部)就足够了。
string (1) | |
---|---|
c-string (2) | |
buffer (3) | |
character (4) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::find_fist_of
函数输入:str - 另一个字符串,包含要搜索的字符
pos - 主串中要搜索的第一个字符的位置,即搜索之后的字符
如果这大于字符串长度,则函数永远不会找到匹配项。
注意:第一个字符由值0(不是1)表示:值为0表示搜索整个字符串。
s - 指向一组字符的指针
如果指定了参数n,则要匹配的序列是数组中的前n个字符。
否则,期望以空终止的序列:要匹配的序列的长度由第一次出现的空字符确定。
n - 要匹配的字符序列的长度
c - 要搜索的字符
函数输出:第一次匹配的第一个字符的位置
如果未找到匹配项,则函数返回string :: npos。
size_t 是无符号整形
=============================================*/
int main()
{
string str ("Please, replace the vowels in this sentence by asterisks.");
size_t found = str.find_first_of("aeiou");
cout << "fist found = " << found << endl;
while (found != string::npos)
{
str[found] = '#';
found = str.find_first_of("aeiou", found + 1);
}
cout << str << '\n';
for(string::iterator it = str.begin(); it < str.end(); it++)
if(*it == '#')
{
str.erase(it);
it--;
}
cout << str << '\n';
return 0;
}
/*===============================================
函数输出:fist found = 2
Pl##s#, r#pl#c# th# v#w#ls #n th#s s#nt#nc# by #st#r#sks.
Pls, rplc th vwls n ths sntnc by strsks.
===============================================*/
find_last_of:
从最后查找字符串中的字符
在字符串中搜索与其参数中指定的任何字符匹配的最后一个字符。
当指定pos时,搜索仅包括位置pos处或之前的字符,忽略pos之后的任何可能的出现。
string (1) | |
---|---|
c-string (2) | |
buffer (3) | |
character (4) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::find_last_of
函数输入:str - 另一个字符串,包含要搜索的字符
pos - 主串中要搜索的最后一个字符的位置,即搜索之前的字符
如果这大于字符串长度,则函数永远不会找到匹配项。
注意:第一个字符由值0(不是1)表示:值为0表示搜索整个字符串。
s - 指向一组字符的指针
如果指定了参数n,则要匹配的序列是数组中的前n个字符。
否则,期望以空终止的序列:要匹配的序列的长度由第一次出现的空字符确定。
n - 要匹配的字符序列的长度
c - 要搜索的字符
函数输出:匹配的最后一个字符的位置
如果未找到匹配项,则函数返回string :: npos。
size_t 是无符号整型
=============================================*/
void SplitFilename (const std::string& str)
{
cout << "Splitting: " << str << '\n';
size_t found = str.find_last_of("/\\"); //在字符串str中查找最后出现斜杠“/”或反斜杠“\”的位置,其中\\表示转意符
cout << " path: " << str.substr(0,found) << '\n'; //后面有讲解,表示从第 0 位字符开始,长度为 found 的字符串,注意第一个字符长度为 1.
cout << " file: " << str.substr(found+1) << '\n'; //从 found + 1 位字符开始,到结束
}
int main()
{
string str1 ("/usr/bin/man");
string str2 ("c:\\windows\\winhelp.exe");
SplitFilename (str1);
SplitFilename (str2);
return 0;
}
/*===============================================
函数输出:Splitting: /usr/bin/man
path: /usr/bin
file: man
Splitting: c:\windows\winhelp.exe
path: c:\windows
file: winhelp.exe
===============================================*/
find_fist_not_of:
在字符串中找不到字符
在字符串中搜索与其参数中指定的任何字符都不匹配的第一个字符。
当POS指定,搜索仅包括字符或在后位置POS,忽略字符之前的任何可能发生。
string (1) | |
---|---|
c-string (2) | |
buffer (3) | |
character (4) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::find_fist_not_of
函数输入:str - 另一个字符串,包含要搜索的字符
pos - 主串中要搜索的第一个字符的位置,即搜索之后的字符
如果这大于字符串长度,则函数永远不会找到匹配项。
注意:第一个字符由值0(不是1)表示:值为0表示搜索整个字符串。
s - 指向一组字符的指针
如果指定了参数n,则要匹配的序列是数组中的前n个字符。
否则,期望以空终止的序列:要匹配的序列的长度由第一次出现的空字符确定。
n - 要匹配的字符序列的长度
c - 要搜索的字符
函数输出:第一次匹配的第一个字符的位置
如果未找到匹配项,则函数返回string :: npos。
size_t 是无符号整型
=============================================*/
int main()
{
string str ("look for non-alphabetic characters...");
size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
if (found != string::npos)
{
cout << "The first non-alphabetic character is " << str[found];
cout << " at position " << found << endl;
}
while(found != string::npos)
{
str[found] = '#';
found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ", found + 1);
}
cout << str << endl;
return 0;
}
/*===============================================
函数输出:The first non-alphabetic character is - at position 12
look for non#alphabetic characters###
===============================================*/
find_last_not_of:
从末尾开始在字符串中查找不匹配的字符
在字符串搜索与其参数中指定的任何字符都不匹配的最后一个字符。
当指定pos时,搜索仅包括位置pos处或之前的字符,忽略pos之后的任何可能的出现。
string (1) | |
---|---|
c-string (2) | |
buffer (3) | |
character (4) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::find_last_not_of
函数输入:str - 另一个字符串,包含要搜索的字符
pos - 主串中要搜索的最后一个字符的位置,即搜索之前的字符
如果这大于字符串长度,则函数永远不会找到匹配项。
注意:第一个字符由值0(不是1)表示:值为0表示搜索整个字符串。
s - 指向一组字符的指针
如果指定了参数n,则要匹配的序列是数组中的前n个字符。
否则,期望以空终止的序列:要匹配的序列的长度由第一次出现的空字符确定。
n - 要匹配的字符序列的长度
c - 要搜索的字符
函数输出:匹配的最后一个字符的位置
如果未找到匹配项,则函数返回string :: npos。
size_t 是无符号整型
=============================================*/
int main()
{
string str ("Please, erase trailing white-spaces \n");
string whitespaces (" \t\f\v\n\r");
size_t found = str.find_last_not_of(whitespaces);
cout << found << str[found] << endl;
if (found != string::npos)
str.erase(found + 1); //len 为默认值,表示从 found + 1,一直删除到结尾
else
str.clear(); // str is all whitespace
std::cout << '[' << str << "]\n";
return 0;
}
/*===============================================
函数输出:34s
[Please, erase trailing white-spaces]
===============================================*/
substr:
生成子字符串
返回一个新构造的字符串对象,其值初始化为此对象的子字符串的副本。
子字符串是对象的一部分,从字符位置pos开始长度为len的字符串(或直到字符串的结尾,以先到者为准)。
string substr(size_t pos = 0,size_t len = npos)const;
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::substr
函数输入:pos - 要复制的第一个字符作为子字符串的位置。
如果这等于字符串长度,则该函数返回一个空字符串。
如果这大于字符串长度,则抛出out_of_range。
注意:第一个字符由值0(不是1)表示。
len - 要包含在子字符串中的字符数
string :: npos的值表示字符串结尾之前的所有字符。
函数输出:一个字符串,是此对象的子对象
=============================================*/
int main()
{
string str="We think in generalities, but we live in details.";
// (quoting Alfred N. Whitehead)
string str2 = str.substr (3,5); // "think"
size_t pos = str.find("live"); // position of "live" in str
string str3 = str.substr (pos); // get from "live" to the end
cout << str2 << ' ' << str3 << endl;
return 0;
}
/*===============================================
函数输出:think live in details.
===============================================*/
compare:
比较字符串
将字符串对象(或子字符串)的值与其参数指定的字符序列进行比较。
该比较字符串是的值的字符串对象或-if使用的签名具有POS和LEN参数-在位置开始在其字符的子POS和跨越LEN字符。
此字符串与比较字符串进行比较,该字符串由传递给函数的其他参数确定。
string (1) | |
---|---|
substrings (2) | |
c-string (3) | |
buffer (4) | |
函数用例
#include <iostream>
#include <string>
using namespace std;
/*==============================================
函数名称:std::string::compare
函数输入:str - 另一个字符串对象,完全(或部分)用作比较字符串
pos - 比较字符串(str1)中第一个字符的位置
如果这大于字符串长度,则抛出out_of_range。
注意:第一个字符由值0(不是1)表示。
len - 比较字符串的长度
string :: npos的值表示字符串结尾之前的所有字符。
subpos, sublen - 与上面的 pos和 len 相同,但指的是另一个用作比较的字符串(str2)
s - 指向一组字符的指针。
如果指定了参数n,则数组中的前n个字符用作比较字符串。
否则,期望以空终止的序列:具有用作比较字符串的字符的序列的长度由第一次出现的空字符确定。
n - 要比较的字符数
函数输出:一个有符号的整数,表示字符串之间的关系
值 比较字符串和比较字符串之间的关系
0 他们相同
<0 不匹配的第一个字符的值在比较字符串中较低,或者所有比较的字符匹配但比较的字符串较短(str1 短)。
>0 比较字符串中不匹配的第一个字符的值更大,或者所有比较的字符匹配但比较的字符串更长。
=============================================*/
int main()
{
string str1 ("green apple");
string str2 ("red apple");
if (str1.compare(str2) != 0)
cout << str1 << " is not " << str2 << '\n';
if (str1.compare(6,5,"applee") < 0)
cout << "still, " << str1 << " is an apple\n";
if (str2.compare(str2.size()-5,5,"apple") == 0)
cout << "and " << str2 << " is also an apple\n";
if (str1.compare(0,str1.size(),str2,4,5) > 0)
cout << "therefore, both are apples\n";
return 0;
}
/*===============================================
函数输出:green apple is not red apple
still, green apple is an apple
and red apple is also an apple
therefore, both are apples
===============================================*/
6.非成员函数重载
getline:
从输入流中获取一行字符到回车符终止获取,空格也获取
注意:cin 是以空格符和回车符作为终止符的
从is中提取字符并将它们存储到str中,直到找到分隔字符delim(或换行符,'\ n')。
如果到达文件末尾或者在输入操作期间发生某些其他错误,则提取也会停止。
如果找到分隔符,则将其提取并丢弃(即不存储它,并且下一个输入操作将在其后开始)。
请注意,调用之前str中的任何内容都将被新提取的序列替换。
每个提取的字符都附加到字符串,就像string的成员push_back 一样。
(1) | |
---|---|
(2) | |
7.静态成员常量
npos:
size_t的最大值,npos是一个静态成员常量值,对于size_t类型的元素具有最大可能值。
当该值用作字符串成员函数中len(或sublen)参数的值时,表示“直到字符串结尾”。 作为返回值,它通常用于表示不匹配。 此常量定义为值-1,由于size_t是无符号整数类型,因此它是此类型的最大可表示值。
static const size_t npos = -1;