码迷,mamicode.com
首页 > 其他好文 > 详细

trim函数

时间:2015-08-27 16:54:13      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

/************************************************************************/
/*   C++ trim函数:去掉字符串最左端和最右端的空白符(包括空格/水平制表符等),
 *              字符串之间的空格就不管它
 *  "  hello word " trim之后变成 “hell word   ”
 *  1 思路:
 *   d 指向字符串的开始位置
 *   c 指向字符串的前端非空白开始位置
 *   b 指向字符串的后端非空白开始位置
 *  存储结构 char data[]
 *  
 *  test1
 *  strlen =12values:  hi world!
    strlen =12values:hi worldld! trim right is wrong

 *  
/************************************************************************/
void mystring::trim2(char *input)
{
    char* pBegin = NULL;//指向字符串的开始位置
    char* pEnd = NULL;//指向字符串的开始位置
    int iNotCharCount = 0;//指向字符串的前端空白个数
    int iCharCount = 0;//指向字符串的前端非空白个数 如何统计
    //trim left
    // 循环条件*pBegin!=‘\0‘  变化条件 pBegin++
    for (pBegin = input; *pBegin!=‘\0‘; pBegin++)
    {  //非空
        if (*pBegin!=‘ ‘)
        {
            break;
        }
        iNotCharCount++;//统计前端空字符个数
    }
    //trim right
    char* pTemp = NULL;

    for (pTemp = pBegin; *pTemp != ‘\0‘; ++pTemp)
    {
        if (*pTemp != ‘ ‘)
        {
            pEnd = pTemp;
        }
        
    }
    //set string endls
    pEnd++;
    *pEnd = ‘\0‘;

    //
    iCharCount = pEnd - pBegin+1;
    
    //change input else you cant return the right values
    if (iNotCharCount>iCharCount)
    {
        strncpy(input, pBegin, iCharCount);
    }
    else
    {  
        memmove(input, pBegin, iCharCount);
        cout << "pBegin=" << pBegin << endl;
        cout << "pEnd=" << pEnd << endl;

    }

}


trim函数

标签:

原文地址:http://my.oschina.net/woyaoxue/blog/498084

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!