在C++中,字符串处理函数是通过标准库中的string类提供的成员函数来实现的。以下是一些常用的C++字符串处理函数:
获取字符串长度
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
// 获取字符串长度
cout << "字符串的长度为: " << str.length() << endl;
return 0;
}
字符串连接
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello, ";
string str2 = "World!";
// 字符串连接
string result = str1 + str2;
cout << result << endl;
return 0;
}
截取子串
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
// 截取子串
string sub = str.substr(7, 5); // 从第7个字符开始,截取5个字符
cout << sub << endl;
return 0;
}
查找子串
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
// 查找子串
size_t found = str.find("World");
if (found != string::npos) {
cout << "子串\"World\"在位置 " << found << " 处被找到" << endl;
} else {
cout << "未找到子串" << endl;
}
return 0;
}
C++的string类还提供了其他的成员函数来进行字符串处理,具体的函数可以根据需求选择使用。