C++ 17 字符串填充函数(PaddingLeft、PaddingRight)填充左侧、右侧。

C++ 17 模版约束

cpp 复制代码
    template <typename T, typename = void>
    struct is_string : std::false_type 
    {
        using value_type = T;
    };

    template <typename T>
    struct is_string<T, 
        std::void_t<
            typename T::value_type,
            typename T::traits_type,
            typename T::allocator_type
        >
    > : std::is_same<
        T,
        std::basic_string<
            typename T::value_type,
            typename T::traits_type,
            typename T::allocator_type
        >
    > 
    {
        using value_type = T;
    };

    // 约束包装器
    template <typename T>
    using if_string = std::enable_if_t<is_string<T>::value, T>;

C++ 模版实现(HPP)

cpp 复制代码
    /// @brief 根据字符串的对齐长度来决定是否需要字符串左侧填充字符
    /// @tparam _Ty 字符串类型
    /// @param s 字符串
    /// @param count 对齐数量
    /// @param padding_char 对齐字符
    /// @return 返回对齐好之后的完整字符串
    template <typename _Ty, typename = stl::if_string<_Ty>>
    _Ty                                                                     PaddingLeft(const _Ty& s, size_t count, typename _Ty::value_type padding_char) noexcept
    {
        size_t str_len = s.size();
        if (count == 0 || count <= str_len) 
        {
            return s;
        }

        // 构造填充字符 + 原字符串
        _Ty result;
        result.reserve(count);

        // 添加填充字符
        result.append(count - str_len, padding_char);

        // 添加原字符串
        result.append(s);
        return result;
    }

    /// @brief 根据字符串的对齐长度来决定是否需要字符串右侧填充字符
    /// @tparam _Ty 字符串类型
    /// @param s 字符串
    /// @param count 对齐数量
    /// @param padding_char 对齐字符
    /// @return 返回对齐好之后的完整字符串
    template <typename _Ty, typename = stl::if_string<_Ty>>
    _Ty                                                                     PaddingRight(const _Ty& s, size_t count, typename _Ty::value_type padding_char) noexcept
    {
        // 构造原字符串 + 填充字符
        _Ty result = s;
        if (count > result.size()) 
        {
            result.resize(count, padding_char);  // 直接在末尾填充
        }

        return result;
    }
相关推荐
wuweijianlove37 分钟前
算法性能的渐近与非渐近行为对比的技术4
算法
研究点啥好呢1 小时前
Github热门项目推荐 | 创建你的像素风格!
c++·python·node.js·github·开源软件
_dindong1 小时前
cf1091div2 C.Grid Covering(数论)
c++·算法
AI成长日志1 小时前
【Agentic RL】1.1 什么是Agentic RL:从传统RL到智能体学习
人工智能·学习·算法
沫璃染墨1 小时前
C++ string 从入门到精通:构造、迭代器、容量接口全解析
c语言·开发语言·c++
黎阳之光1 小时前
黎阳之光:视频孪生领跑者,铸就中国数字科技全球竞争力
大数据·人工智能·算法·安全·数字孪生
skywalker_111 小时前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
wfbcg2 小时前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒2 小时前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode