您的位置:首页 > 职场人生

面试题 - 统计字符串中字符的个数

2015-09-08 14:53 423 查看
#include <string>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

void countSameChar(char* s, char* d)
{
char* p = s;
char* q = s;

while(*q != '\0')
{
if(*p == *q)
{
q++;
}
else
{
char temp[20];
itoa(q-p, temp, 10);
*d++ = *p;

for(int i=0; i<strlen(temp); i++)
{
*d = temp[i];
d++;
}

p = q;
}
}

//处理最后一个单词
char temp[20];
itoa(q-p, temp, 10);
*d++ = *p;

for(int i=0; i<strlen(temp); i++)
{
*d = temp[i];
d++;
}

*d = '\0';
}

int main()
{
char source[] = "aabbbcccccccccccddddddddddddddddddddddddddd";
char dest[20];

countSameChar(source, dest);
printf("%s\n", dest);  //a2b3c11d27
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: