C++ std::string扩展

 strUtil.h

#pragma once
#include <cctype>
#include <vector>
#include <memory>
#include <sstream>
#include <type_traits>
#include <string_view>
#include <algorithm>

namespace cpv {
	/** Return whether string starts with given pattern */
	static inline bool startsWith(std::string_view str, std::string_view pattern) {
		return (str.size() >= pattern.size() &&
			str.substr(0, pattern.size()) == pattern);
	}

	/** Return whether string ends with given pattern */
	static inline bool endsWith(std::string_view str, std::string_view pattern) {
		return (str.size() >= pattern.size() &&
			str.substr(str.size() - pattern.size()) == pattern);
	}

	/**
	 * Split string with specified characters.
	 * Call func(parts, count) while split.
	 * Default split characters are empty characters.
	 */
	template <class Func>
	void splitString(
		std::string_view str, const Func& func, const char* delimiter = " \t\r\n") {
		std::size_t startIndex = 0;
		std::size_t count = 0;
		while (startIndex < str.size()) {
			auto index = str.find_first_of(delimiter, startIndex);
			auto endIndex = (index == str.npos) ? str.size() : index;
			func(str.substr(startIndex, endIndex - startIndex), count);
			index = str.find_first_not_of(delimiter, endIndex);
			startIndex = (index == str.npos) ? str.size() : index;
			++count;
		}
	}

	/**
	 * Split string with specified characters.
	 * Call func(parts, count) while split.
	 * Single char version for better performance.
	 */
	template <class Func>
	void splitString(std::string_view str, const Func& func, char delimiter) {
		std::size_t startIndex = 0;
		std::size_t count = 0;
		while (startIndex < str.size()) {
			auto index = str.find_first_of(delimiter, startIndex);
			auto endIndex = (index == str.npos) ? str.size() : index;
			func(str.substr(startIndex, endIndex - startIndex), count);
			index = str.find_first_not_of(delimiter, endIndex);
			startIndex = (index == str.npos) ? str.size() : index;
			++count;
		}
	}

	/**
	 * Join arguments into string.
	 * This function is very slow, don't call it where performance is important.
	 */
	template <class Delimiter, class... Args>
	std::string joinString(Delimiter&a
### 关于 `std::string` 的基本用法 在 C++ 中,`std::string` 是标准库提供的一种用于处理字符串数据类型的容器类。它位于头文件 `<string>` 中,因此在使用前需通过 `#include <string>` 引入。 #### 创建和初始化 可以通过多种方式创建并初始化一个 `std::string` 对象: ```cpp #include <iostream> #include <string> int main() { std::string str1; // 默认构造函数,str1为空字符串 std::string str2("hello"); // 使用常量字符数组初始化 std::string str3(5, 'a'); // 初始化为包含五个'a'的字符串 std::string str4(str2); // 复制构造函数 std::cout << "str1: " << str1 << "\n"; std::cout << "str2: " << str2 << "\n"; std::cout << "str3: " << str3 << "\n"; std::cout << "str4: " << str4 << "\n"; return 0; } ``` #### 常见操作 以下是几个常用的成员函数及其功能: - **访问单个字符**: 可以像数组一样索引字符串中的某个位置上的字符。 ```cpp char c = str2[1]; // 获取第二个字符 (注意:下标从零开始) ``` - **获取长度**: 返回当前存储的有效字符数。 ```cpp size_t length = str2.length(); // 或者 size() ``` - **拼接字符串**: 将两个或者多个字符串连接起来形成一个新的较长字符串。 ```cpp std::string combined = str2 + " world"; // 结果:"hello world" combined += "!"; // 追加感叹号到末尾 ``` - **查找子串**: 查找指定子串首次出现的位置;如果未找到,则返回 `std::string::npos`。 ```cpp size_t pos = str2.find("ll"); if(pos != std::string::npos){ std::cout << "'ll' found at position: " << pos << '\n'; } else{ std::cout << "'ll' not found\n"; } ``` - **替换部分字符串**: 替换掉原字符串某一段的内容。 ```cpp str2.replace(1, 2, "XX"); // 把从第1位起连续两位替换成"XX", 结果变为"hXXo" ``` #### 需要注意的问题 尽管 `std::string` 提供了许多便利的功能,在实际编程过程中仍需要注意一些潜在陷阱或常见错误: 1. **越界访问** 如果尝试访问超出范围的元素会引发未定义行为。应始终验证索引是否有效再执行相应动作[^1]。 2. **修改只读对象** 当试图改变由字面值转换而来的临时 string 实例时也会触发异常情况。例如下面这段代码就会失败因为右值不可变特性所致[^2]: ```cpp const char* literal = "immutable"; std::string s(literal); s[0] = 'M'; // 正确做法应该是先复制成非 const 类型后再更改 ``` 3. **性能考量** 不断地追加短小片段至大型字符串可能会引起频繁重新分配内存空间从而降低效率。可以预先估算最终大小并通过 reserve 方法预留足够的容量来优化此过程. ```cpp std::string buffer; buffer.reserve(estimated_size); // 减少动态扩展次数提升效能 for(auto& item : items){ buffer.append(item); } ``` ### 总结 以上介绍了有关如何正确有效地运用 C++ 标准模板库里的 string 容器的一些基础知识以及可能遇到的风险点提示。合理利用这些工具能够极大简化日常开发工作同时也提高了程序健壮性与运行速度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码力码力我爱你

创作不易,小小的支持一下吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值