有关字符串的技巧模板

先列一下string 的常见操作
s.find(x)
用于查找并返回子字符串或字符在s中第一次出现的位置,若找不到返回std::npos;
若为s.find(x,1)即为从第一个位置开始往后查找

点击查看代码
std::string str = "Hello World";
std::cout << str.find("World"); // 输出:6

s.size()
返回s的长度

点击查看代码
std::string str = "Hello";
std::cout << str.size(); // 输出:5

s.append()
在字符串的末尾添加另一个字符串s=helloworld

点击查看代码
std::string str1 = "Hello";
str1.append(" World");
std::cout << str1; // 输出:Hello World

s.replace

点击查看代码
std::string str = "Hello World";
str.replace(str.find("World"), 5, "Universe");
std::cout << str; // 输出:Hello Universe

s.empty()

点击查看代码
std::string str = "";
std::cout << std::boolalpha << str.empty(); // 输出:true字符串为空

寻找子串在字符串中出现的次数

点击查看代码
#include <iostream>
#include <string>
int countSubstring(const std::string& str, const std::string& sub) {
int count = 0;
size_t pos = 0;
while ((pos = str.find(sub, pos)) != std::string::npos) {
++count;
pos += sub.length(); // 避免重复计数
}
return count;
}
int main() {
std::string text = "I am gonna talk about chatgpt, and Chatgpt, and CHATGPT chatgpt";
std::string target = "chatgpt";
// 不区分大小写统计
int count = 0;
for (char c : text) {
c = std::tolower(c); // 将所有字符转换为小写
}
for (char c : target) {
c = std::tolower(c); // 将目标子串转换为小写
}
count = countSubstring(text, target);
std::cout << "The substring \"" << target << "\" appears " << count << " times." << std::endl;
return 0;
}

获取子串的函数

点击查看代码
int main() {
std::string str = "Hello, World!";
// 提取从位置 0 开始,长度为 5 的子串
std::string sub1 = str.substr(0, 5);
std::cout << sub1 << std::endl; // 输出 "Hello"
// 提取从位置 7 开始到字符串末尾的子串
std::string sub2 = str.substr(7);
std::cout << sub2 << std::endl; // 输出 "World!"
// 如果起始位置或长度超出了字符串的范围,将会抛出 std::out_of_range 异常
// std::string sub3 = str.substr(20); // 这会抛出异常
return 0;
}

posted on   swj2529411658  阅读(9)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示