substr()
substr() 函数可以提取 string 字符串中的子字符串,该函数有两个参数,第一个参数为需要提取的子字符串的起始下标,第二个参数是需要提取的子字符串的长度。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "first second third";
string s2;
s2 = s1.substr(6, 6);
cout<< s1 <<endl;
cout<< s2 <<endl;
return 0;
}
first second third
second
该函数同样会出现参数越界的情况,如果第一个参数越界,则函数会抛出异常。在第一个参数没有越界的情况下,第二个参数仍然会导致越界,该函数的处理方式与前面提到的 erase() 函数、replace() 函数相同,子字符串最多从第一个参数所指明的下标开始一直延续到字符串结尾。
find()
find() 函数可以在字符串中查找子字符串中出现的位置。该函数有两个参数,第一个参数是待查找的子字符串,第二个参数是表示开始查找的位置,如果第二个参数不指名的话则默认从 0 开始查找,也即从字符串首开始查找。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "first second third";
string s2 = "second";
int index = s1.find(s2,5);
if(index < s1.length())
cout<<"Found at index : "<< index <<endl;
else
cout<<"Not found"<<endl;
return 0;
}
rfind() 函数与 find() 函数很类似,同样是在字符串中查找子字符串。不同的是,find() 函数是从第二个参数开始往后查找,而 rfind() 函数则是最多查找到第二个参数处,如果到了第二个参数所指定的下标还没有找到子字符串,则返回一个无穷大值 4294967295。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "t second third";
string s2 = "second";
int index = s1.rfind(s2,6);
if(index < s1.length())
cout<<"Found at index : "<< index <<endl;
else
cout<<"Not found"<<endl;
return 0;
}
find_first_of()
find_first_of() 函数是用于查找子字符串和字符串共同具有的字符在字符串中出现的位置。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "first second second third";
string s2 = "asecond";
int index = s1.find_first_of(s2);
if(index < s1.length())
cout<<"aaaFound at index : "<< index <<endl;
else
cout<<"aaaaNot found"<<endl;
return 0;
}
find_first_not_of
而 find_first_not_of() 函数则相反,它查找的是在 s1 字符串但不在 s2 字符串中的首位字符的下标,如果查找不成功则返回无穷大。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "secondasecondthird";
string s2 = "asecond";
int index = s1.find_first_not_of(s2);
if(index < s1.length())
cout<<"Found at index : "<< index <<endl;
else
cout<<"Not found"<<endl;
return 0;
}
在本例中在 s1 但是不在 s2 中的首字符是 ‘t’,其所在下标为 13,故而返回下标 13。
C++字符串的比较
==、!=、<=、>=、<和>操作符都可以用于进行 string 类型字符串的比较,这些操作符两边都可以是 string 字符串,也可以一边是 string 字符串另一边是字符串数组。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "secondsecondthird";
string s2 = "secondthird";
if( s1 == s2 )
cout<< " == " <<endl;
if( s1 != s2 )
cout<< " != " <<endl;
if( s1 < s2 )
cout<< " < " <<endl;
if( s1 > s2 )
cout<< " > " <<endl;
return 0;
}
---------------------
作者:静思心远
来源:CSDN
原文:https://blog.csdn.net/zhiyuan2021/article/details/123037286
版权声明:本文为作者原创文章,转载请附上博文链接!
内容解析By:CSDN,CNBLOG博客文章一键转载插件