6.4 C++提取子字符串及字符串的比较

时间:2023-03-10 04:28:48
6.4 C++提取子字符串及字符串的比较

参考:http://www.weixueyuan.net/view/6393.html

总结:

  函数substr可以提取string字符串中的子字符串,该函数有两个参数,第一个参数为需要提取的子字符串的起始下标,第二个参数是需要提取的子字符串的长度。

  “==”、 “!=”、 “<=”、 “>=”、 “<”和“>”操作符都可以用于进行string类型字符串的比较,这些操作符两边都可以是string字符串,也可以一边是string字符串另一边是字符串数组。

函数substr可以提取string字符串中的子字符串,该函数有两个参数,第一个参数为需要提取的子字符串的起始下标,第二个参数是需要提取的子字符串的长度。

例1:

#include <iostream>
#include <string>
using namespace std; int main()
{
string s1 = "first second third";
string s2;
s2 = s1.substr(, );
cout<< s1 <<endl;
cout<< s2 <<endl;
return ;
}

程序运行结果:
first second third
second

该函数同样会出现参数越界的情况,如果第一个参数越界则函数会抛出异常。在第一个参数没有越界的情况下,第二个参数仍然会导致越界,该函数的处理方式与前面提到的erase函数、replace函数相同,子字符串最多从第一个参数所指明的下标开始一直延续到字符串结尾。

C++字符串的比较

参考:http://www.weixueyuan.net/view/6395.html

“==”、 “!=”、 “<=”、 “>=”、 “<”和“>”操作符都可以用于进行string类型字符串的比较,这些操作符两边都可以是string字符串,也可以一边是string字符串另一边是字符串数组。

例1:

 
#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 ;
}

程序最终运行结果:
!=
<