问题
需要在字符串中插入字符统计的个数。例如字符串aaab,插入字符个数后变成aaa3b1;
代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXCOUNT 2*100
char *transformation(char *str)
{
int len = strlen(str);
char *buf = new char[len+1];
char *p = str;
char *q = p+1;
int count =1;
while(*q)
{
if(*p ==*q)
{
count++;
p++;
q++;
}
else
{
itoa(count,buf,10);
int nbits = strlen(buf);
strcat(buf,q);
*q = 0;
strcat(str,buf);
q+=nbits;
p = q;
q = p +1;
count =1;
}
}
itoa(count,buf,10);
strcat(str,buf);
delete [] buf;
buf = NULL;
return str;
}
int main()
{
char str[MAXCOUNT];
scanf("%s",&str); //aaabbcccdee
printf("%s\n",str); //aaabbcccdee
char *pstr = transformation(str);
printf("%s\n",pstr); //aaa3bb2ccc3d1ee2
return 0;
}
本文介绍了一种在字符串中插入字符出现次数的方法。通过遍历字符串并统计连续相同字符的数量,在每个不同字符间插入相应的计数。该方法使用 C 语言实现,并附带了一个完整的示例代码。
171万+

被折叠的 条评论
为什么被折叠?



