一、字符串的拼接
string
类提供了两种方式来进行字符串的拼接操作,一种是使用 +
运算符,另一种是使用成员函数 append()
。
使用 +
运算符
string str1 = "Hello ";
string str2 = "world!";
string str3 = str1 + str2;
在以上代码中,通过使用 +
运算符,将 str1
与 str2
拼接起来,并将结果存储在 str3
中。这个方法的优点是简单易懂,但是当需要拼接的字符串较多时,使用 +
操作符可能会产生一些性能问题。
使用成员函数 append()
string str1 = "Hello ";
string str2 = "world!";
str1.append(str2);
在以上代码中,通过使用成员函数 append()
,将 str2
拼接到了 str1
的尾部。这个方法的优点是可以拼接任意数量的字符串,而且效率较高。
二、字符串的比较
string
类提供了多种方式进行字符串的比较,包括 ==
、!=
、<
、>
、<=
、>=
等运算符,以及成员函数 compare()
。
使用运算符
string str1 = "apple";
string str2 = "banana";
bool result = (str1 == str2);
在以上代码中,使用 ==
运算符比较了两个字符串的内容,然后将结果存储在了 result
变量中。
使用成员函数 compare()
string str1 = "apple";
string str2 = "banana";
int result = str1.compare(str2);
在以上代码中,使用成员函数 compare()
比较了两个字符串的内容,返回的结果可以分为三种情况:
- 如果
str1
等于str2
,返回0
; - 如果
str1
小于str2
,返回一个负数; - 如果
str1
大于str2
,返回一个正数。
三、字符串的查找
string
类提供了多种方法进行字符串的查找,包括成员函数 find()
、rfind()
、find_first_of()
、find_last_of()
等。
使用成员函数 find()
string str = "hello world";
int pos = str.find("world");
在以上代码中,使用成员函数 find()
查找了子串 "world"
在字符串中第一次出现的位置,并将结果存储在了 pos
变量中。如果没有找到,会返回 string::npos
。
使用成员函数 rfind()
string str = "hello world";
int pos = str.rfind("o");
在以上代码中,使用成员函数 rfind()
查找字符 "o"
在字符串中最后一次出现的位置,并将结果存储在了 pos
变量中。如果没有找到,会返回 string::npos
。
使用成员函数 find_first_of()
string str = "hello world";
int pos = str.find_first_of("aeiou");
在以上代码中,使用成员函数 find_first_of()
查找字符串中第一个元音字母的位置,并将结果存储在了 pos
变量中。如果没有找到,会返回 string::npos
。
使用成员函数 find_last_of()
string str = "hello world";
int pos = str.find_last_of("aeiou");
在以上代码中,使用成员函数 find_last_of()
查找字符串中最后一个元音字母的位置,并将结果存储在了 pos
变量中。如果没有找到,会返回 string::npos
。
四、字符串的替换
string
类提供了成员函数 replace()
进行字符串的替换操作,其语法为:
string& replace(size_t pos, size_t len, const string& str);
其中,pos
表示要开始替换的位置,len
表示要替换的子串的长度,str
表示用来替换的字符串。
使用成员函数 replace()
string str = "hello world";
str.replace(0, 5, "hi");
在以上代码中,通过使用 replace()
函数,将字符串 "hello"
替换成了 "hi"
,得到了新的字符串 "hi world"
。
五、字符串的分割
string
类本身并没有提供字符串的分割函数,但是可以结合 sstream
头文件中的 stringstream
类进行字符串的分割。
使用 stringstream
类进行字符串的分割
string str = "apple,banana,orange";
stringstream ss(str);
string temp;
vector<string> vec;
while (getline(ss, temp, ',')) {
vec.push_back(temp);
}
在以上代码中,首先将字符串 str
放入了一个 stringstream
对象中,然后使用 getline()
函数和逗号为分隔符将字符串分割成若干子串,并将它们存储在了 vector
容器中。