ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

C++字符串处理函数

C++字符串处理函数

在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类还提供了其他的成员函数来进行字符串处理,具体的函数可以根据需求选择使用。

返回列表