zoukankan      html  css  js  c++  java
  • 封装字符串的Format操作

    相信即使再讨厌MFC的朋友也不会把厌恶牵扯到CString类上,
    而且CString现在也提升为ATL和MFC的共享类。用CString类,
    当然不能忘记它的Format方法,其用于格式化字符串。示例操作如下:
    CString  strDemo;
    strDemo.Format( _T("数字为:%d, 字符串为:%s"), 1, strOther );

    很简单的使用.但我总觉得用的太多代码不美观(或许我有点洁癖吧),我总觉得一行代码
    的事用两行代码有点多余,于是我封装了StringFormatEx类.该类的封装风格借鉴了
    ATL的字符串转换类的风格(如CA2TEX、CT2WEX等),
    代码如下:

    复制代码
    /*
    * 格式化字符串
    */
    template< int t_nBufferLength = 128 >
    class StringFormatEx
    {
    public:
        StringFormatEx( PCTSTR pszFormat, ) throw()
        {
            va_list ptr; 
            va_start(ptr, pszFormat);

            CString strFormat;
            strFormat.FormatV( pszFormat, ptr );

            ASSERT( t_nBufferLength > strFormat.GetLength() );

            _stprintf_s( m_szBuffer, strFormat );

            va_end(ptr);
        }

        operator LPCTSTR() throw()
        {
            return (m_szBuffer);
        }

    private:
        TCHAR m_szBuffer[t_nBufferLength];

    private:
        StringFormatEx( const StringFormatEx& ) throw();
        StringFormatEx& operator=( const StringFormatEx& ) throw();
    };

    typedef StringFormatEx<> StringFormat;
    复制代码

    使用示例:

    //void Test( LPCTSTR lpsz ){}

    Test( StringFormat( _T("数字为:%d, 字符串为:%s"), 1, strOther  ) );

  • 相关阅读:
    I Hate It(线段树点修改区间查询)
    DFS(dfs)
    时间复杂度和空间复杂度的简单讲解
    [转]matlab读取cvs文件的几种方法
    适合小白的大白话讲解 --->Git 与 Github 的区别
    [转]串口、COM口、UART口, TTL、RS-232、RS-485区别详解
    Pandas学习之(一)
    正规表示法
    Numpy解决问题实例--随机漫步
    Python 中range和xrange的详细区别
  • 原文地址:https://www.cnblogs.com/zhaodahai/p/6825486.html
Copyright © 2011-2022 走看看