`TrimXXX` in WTL::CString should be `TrimAnyOfXXX`

`CString` is a powerful utility in our daily programming. But recently I found something intuitive and error prone.

 

I have such task:

  •   To make sure the file path is end with `360sd`, such as 'c:\program files' -> 'c:\program files\360sd'; but 'c:\program files\360sd' will keep unchanged.
/**
 *        You have to make sure the return value is 
 *    end up with `360sd`.
 */
CString MyTask(const CString path)
{
    // TODO: 
}

 

How to do? Amm... It's easy, we have `CString`.

/**
 *        Make sure the return value is end up with `360sd`.
 */
CString MyTask(CString path)
{
    static const CString sc_tail = L"\\360sd";

    path.TrimRight(sc_tail);
    return path + sc_tail;
}

 

Looks so easy and nice. Let's do some test:

MyTask(L"c:\\abc")                   =>   "c:\\abc\\360sd"                     suc

MyTask(L"c:\\abc\\")                =>   "c:\\abc\\360sd"                      suc

MyTask(L"c:\\program files")    =>   "c:\\program file\\360sd"        fail

 

Surprising isn't it?

Let's see such codes:

    CString str;

    // `TrimLeft`.
    str = CString(L"aabbccddaabb").TrimLeft(L"a");       // aabbccddaabb
    str = CString(L"aabbccddaabb").TrimLeft(L"ax");      // aabbccddaabb
    str = CString(L"aaaabbbbcccc").TrimLeft(L"ab");      // ababababcccc
    str = CString(L"ababbbbaaacc").TrimLeft(L"ab");      // ababababcccc

    // `TrimRight`.
    str = CString(L"888881122111").TrimRight(L"21");     // 888881122111
    str = CString(L"111111212121").TrimRight(L"21");     // 888881122111

 

See the `TrimXXX` source code:

That means, `TrimXXX` actually is remove all chars in argument in one direction, untill none of char in argument is removed.

I think the function name should be `TrimAnyOfXXXX`.

God bless!

 

posted @ 2013-11-08 18:17  walfud  阅读(261)  评论(0编辑  收藏  举报