/************************************************************************
转换字符串格式为原来字符串里的字符+该字符连续出现的个数,
例如:1233422222 转换为1121324125(1出现1次,2出现1次,3出现2次......
*************************************************************************/
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
void convert(char input[],char output[])
{
int count = 1;
char *fast = input;
char *slow = input;
while(*(++fast)!='\0')
{
if(*fast == *slow)//如果当前读入的字符和正在统计的一样,那么出现次数要++
{
count++;
continue;
}
// 当快慢指针不同时就执行下边语句
if(slow<fast) //注意不能写成while 形式 因为要求重复的数字只出现一次
{
*output++=*slow++;
}
*output++=count+'0'; //将出现次数添加至数字后边
slow = fast; // 慢指针指向快指针 重新统计
count = 1; //计数器重置为初始值
}
*output++=*slow; // 快指针跳出循环时慢指针仍没有跳出循环但是count计数正确
*output++=count+'0';//因为读到'\0'循环退出,最后一个连续的字符序列没有输出,所以在这里追加输出
*output='\0';
}
int main()
{
char input[]="1233422222";
char output[30]={0};
convert(input,output);
cout<<"output is "<<output<<endl;
}
转换字符串格式为原来字符串里的字符+该字符连续出现的个数
最新推荐文章于 2018-07-17 22:57:30 发布