有关字符串的技巧模板
先列一下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 2024-01-27 03:50 swj2529411658 阅读(30) 评论(0) 收藏 举报
浙公网安备 33010602011771号