当前位置:编程学习 > C/C++ >>

转换字符串格式为原来字符串里的字符+该字符连续出现的个数

[cpp]
/************************************************************************
转换字符串格式为原来字符串里的字符+该字符连续出现的个数,
例如: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; 

  
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,