1. 程式人生 > >C++ 實現字串壓縮

C++ 實現字串壓縮

字串壓縮:
#include <iostream>
using namespace std;
string myZIP(string str);


string myZIP(string str)
{
    string zip;	//"aaaabbndaa"壓縮後a4b2nda2
    int  n = 1;
    for(int i=0;i<str.length();i++)
    {
        if(str[i]==str[i+1])
        {
            n++;
        }
        else
        {
//int convert to string
            char tmp[5];
            sprintf(tmp,"%d",n);//將整型變為char
            string str_n = tmp;//將char變為string,方便進行字元的+運算
            zip += str[i];
            if(n!=1)
                zip += str_n;
            n = 1;
        }

    }
    return zip;
}
int main()
{
    string str = "";//壓縮後a4b2nda2
    cout<<myZIP(str)<<endl;
    return 0;
}