一、获取字符串长度
C++ string库中提供了length和size函数用于获取字符串的长度,返回值类型都是size_t,示例代码如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
cout << "Length: " << str.length() << endl;
cout << "Size : " << str.size() << endl;
return 0;
}
输出结果:
Length: 11 Size : 11
二、字符串查找
string库中提供了多种函数用于查找字符串中特定字符或子字符串的位置,其中常用的是find函数和rfind函数。find函数从字符串的头部开始查找,rfind函数从字符串的尾部开始查找,两个函数都返回第一个匹配字符串的位置,如果没有找到则返回string::npos。示例代码如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
int pos1 = str.find("l");
int pos2 = str.rfind("l");
int pos3 = str.find("World");
int pos4 = str.find("world");
cout << "pos1: " << pos1 << endl;
cout << "pos2: " << pos2 << endl;
cout << "pos3: " << pos3 << endl;
cout << "pos4: " << pos4 << endl;
return 0;
}
输出结果:
pos1: 2 pos2: 9 pos3: 6 pos4: -1
三、字符串替换
string库中提供了replace函数用于替换字符串中的某个子串。该函数的参数包括被替换子串的位置、长度和替换字符串,示例代码如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
str.replace(6, 5, "Li Lei");
cout << str << endl;
return 0;
}
输出结果:
Hello Li Lei
四、字符串截取
string库中提供了substr函数用于从字符串中截取一部分。该函数的参数包括起始位置和截取长度,如果不提供截取长度则默认截取到字符串末尾。示例代码如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
string sub1 = str.substr(3, 5);
string sub2 = str.substr(6);
cout << sub1 << endl;
cout << sub2 << endl;
return 0;
}
输出结果:
lo Wo World
五、字符串拼接
string库中提供了多种方式用于字符串的拼接,其中常用的是+运算符和append函数。+运算符用于将两个字符串连接起来,append函数用于在字符串末尾追加另一个字符串。示例代码如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello ";
string str2 = "World";
string str3 = str1 + str2;
string str4 = str1.append(str2);
cout << str3 << endl;
cout << str4 << endl;
return 0;
}
输出结果:
Hello World Hello World
六、字符串分割
对于需要将字符串按照指定字符分割成多个子串的场景,可以使用stringstream类和getline函数。示例代码如下:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str = "apple,banana,orange";
stringstream ss(str);
string item;
while (getline(ss, item, ',')) {
cout << item << endl;
}
return 0;
}
输出结果:
apple banana orange
以上就是使用C++ string函数实现字符串相关操作的相关内容。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/254659.html
微信扫一扫
支付宝扫一扫