*** 自写代码:在字符串中插入连续字符的个数

例如字符串aabbbc,插入字符个数后变成aa2bbb3c1

#include <iostream>
#include <string.h>
using namespace std;
char * strInsertCount (const char * str)
{
    if (str==NULL) return NULL;
    char * retStr = new char[strlen(str)*2+1];
    char * p = retStr;
    int count = 1;
    while ((*p++=*str++) != '\0')
    {
        if (*str==*(str-1))
        {
            count++;
        }
        else
        {
            *p++ = count + '0';
            count = 1;
        }
    }
    return retStr;
}
int main()
{
    char a[] = "aadiiiisasbbbeewww";
    char * p = strInsertCount (a);
    cout << "Input:  " << a <<endl;
    cout << "Output: " << p << endl;
    delete [] p;
    return 0;
}

 

posted @ 2018-12-23 19:15  super行者  阅读(251)  评论(0编辑  收藏  举报