C++中的string类是一个非常有用的类,它可以帮助我们快速完成字符串处理。下面我们就来看一下string类的高级用法:
1. 字符串拼接
字符串拼接是指将两个字符串拼接在一起,形成一个新的字符串。string类提供了append()函数来实现字符串拼接,具体使用方法如下:
string s1 = "hello"; string s2 = "world"; string s3 = s1.append(s2);
这样,s3就是"helloworld"了。
2. 字符串替换
字符串替换是指将某个字符串中的某个字符替换成另一个字符。string类提供了replace()函数来实现字符串替换,具体使用方法如下:
string s1 = "hello world"; string s2 = s1.replace(5, 5, "my");
这样,s2就是"hello my world"了。
3. 字符串查找
字符串查找是指查找字符串中是否存在某个字符。string类提供了find()函数来实现字符串查找,具体使用方法如下:
string s1 = "hello world"; size_t pos = s1.find("world");
这样,pos就是6,也就是"world"在字符串s1中的位置。
4. 字符串分割
字符串分割是指将一个字符串按照某个字符分割成多个字符串。string类提供了substr()函数来实现字符串分割,具体使用方法如下:
string s1 = "hello world"; string s2 = s1.substr(0, 5); string s3 = s1.substr(6);
这样,s2就是"hello",s3就是"world"。
5. 字符串比较
字符串比较是指比较两个字符串的大小。string类提供了compare()函数来实现字符串比较,具体使用方法如下:
string s1 = "hello"; string s2 = "world"; int res = s1.compare(s2);
这样,res就是-1,表示s1小于s2。
以上就是,它可以帮助我们实现字符串的拼接、替换、查找、分割、比较等操作,是非常实用的类。