在算法竞赛中,经常碰到字符串题目,一般来说,要避免使用字符数组,所以我一般使用string类进行字符串操作。
string类里面包含了许多有用的成员函数,肥肠好用!
string赋值
如下:
string s1 ;
string s2 ;
s1 = "hello world!"
s2 = s1 ;
在上述代码片中,s1可以在声明时赋值,s2可以用s1直接赋值。
字符串拼接
string s1 = "hello ";
string s2 = "world " ;
srting s = s1 + s2 ;
很明显,字符串拼接可以用 + 号连接, 减 号是没有用的。 注意一点,若s本来就不为空,进行第三行操作后,也是被覆盖为s1+s2 。
字符串追加
在上面的拼接中,可以知道,若s不为空,进行拼接的话会被覆盖,那怎么进行追加呢?
利用 append 函数进行操作。
string s1 = "hello"
string s2 = "world";
s1.append(s2);
输出 s1 就是 hello world ! 当然也可以 string s3 = s1 + s2 !
字符串比较
string s1 = "hello"
string s2 = "Hello"
string s3 = "world"
string s4 = "world"
bool flag1 = s1 == s2 ;
bool flag2 = s1 != s3 ;
bool flag3 = s3 == s4 ;
进行字符串比较,利用 “==” 和 “!=” 两个符号进行比较,如果为真,就flag就是true。
注意一点,区分大小写!
字符串反转
引入算法头文件 algorithm
string s = "hello world"
s.reverse(s.begin(),s.end());
注意,参数为迭代器!
字符串插入
在string类中,字符串插入有很多重载函数,下面是我常用的一个:
string s ;
s = "hello"
s.insert(5,"world")
输出** s** 就是helloworld 。
注意点:①第一个参数是插入字符串的位置。②位置:比如 “5” ,那就是字符串s中的**“o”**的后一位。③插入的时候位置一定要选择你要插入的那个位置的后一位,如果上述的示例参数填“4”,那么就是从“o”那里插入,s就会变成“hellworldo”。
体会体会里面的细节!
字符串删除操作
用到的是erase()函数。
一、先来讲删除某个字符的问题
函数为 : erase( it )
it为迭代器的意思。
string s = "hello world "
s.erase(s.begin() + 5 );
cout << s << endl ;
参数为迭代器,删除迭代器所指的字符。
二、再来讲讲删除子串的问题
有两个重载:
① erase( int pos , int len ) .
string s = "hello"
s.erase(2,2)
cout << s << endl;
第一个参数是删除位置,第二个参数是删除的长度,就是从pos开始删除后面长度为len的子串
示例中 输出 s 为 " heo "
② erase (it first , it end )
string s ;
s = "abcdefg" ;
s.erase(s.begin()+1,s.begin()+5);
cout << s << endl ;
最后输出的是 afg 。值得注意的点,为什么 “f” 没有被删除呢? 因为删除的结束位置,到迭代器前一个,意思就是这是个左闭右开的区间 [a,b) ,这个要记住!