c语言字符串如何压缩

一道作业,问题给了一个数组A(字符串形式),要求把它转换成压缩形式的B数组(整型),比如AAAABBBBCCD-->4A4BCCD,两个一样的字母不变。同时要求调用三个函数,一个用来压缩(变量是A,B两个数组),一个用来print B数组,一个把B数组还原回原字符串print。

话说B数组不应该是整形呀,不然不能保存字母了。以下是我的代码。。。

#include <iostream>

#include <string.h>

#include <stdio.h>

using namespace std;


void yasuo(char a[],char b[])

{

    int count=1,p=0;

    for(int i=0; i<strlen(a); i++)

        if(a[i]==a[i+1])

            count++;

        else if(count>2)

        {

            b[p++]=(char)(count+'0');

            b[p++]=a[i];

            count=1;

        }

        else if(count==2)

        {

            b[p++]=a[i];

            b[p++]=a[i];

            count=1;

        }

        else

            b[p++]=a[i];

}

void printB(char b[])

{

    cout<<b<<endl;

}

void backB(char b[])

{

    for(int i=0; i<strlen(b); i++)

        if(b[i]<='9'&&b[i]>='3')

        {

            for(int j=0; j<(int)(b[i]-'0'); j++)

                cout<<b[i+1];

            i++;

        }

        else

            cout<<b[i];

    cout<<endl;

}

int main()

{

    char a[1000]= {0},b[1000]= {0};

    gets(a);

    yasuo(a,b);

    printB(b);

    backB(b);

}

追答

满意请采纳(⊙o⊙)哦!

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-03-13
/*b数组可以是整形呀*/
#define SRC_MAX 50
#define DEST_MAX 100
void yasuo(char * srcArray, int dstArray[])
{
    char * p = srcArray;
    char savedChar = *p;
    int count = 1;
    int dstIndex = 0;
    p++;
    while (*p)
    {
        if (*p == savedChar)
        {
            count ++;
        }
        else
        {
            dstArray[dstIndex] = count;
            count = 1;
            dstIndex++;
            dstArray[dstIndex] = savedChar;
            savedChar =  *p;
            dstIndex++;
        }
        p++;
    }
    if (*p == NULL)
    {
        dstArray[dstIndex] = count;
        dstArray[dstIndex+1] = savedChar;
        return;
    }
}

void dayin(int arr[])
{
    for (int i = 0; i < DEST_MAX; i=i+2)
    {
        if (arr[i])
        {
            printf("%d%c",arr[i], arr[i+1]);
        }
    }
    printf("\n");
}

void huanyuan(int arr[])
{
    for (int i = 0; i < DEST_MAX; i=i+2)
    {
        if (arr[i])
        {
            for (int j = 0; j < arr[i]; j++)
            {
                printf("%c",arr[i+1]);
            }
        }
    }
    printf("\n");
}

int main()
{
    printf("shu ru zi fu chuan :\n");
    char a [SRC_MAX] = {0};
    gets(a);
    int b[DEST_MAX] = {0};
    yasuo(a, b);
    dayin(b);
    huanyuan(b);
}

第2个回答  2016-03-02
  如果数据结构是数组的话,主要是要解决两个问题,一是统计重复的字符,二是确定数组压缩后每个元素在数组中所处的位置。
  可以用一个指针遍历数组,另一个指针标记存储位置。
  字符串或串(String)是由数字、字母、下划线组成的一串字符。一般记为 s="a1a2···an"(n>=0)。它是编程语言中表示文本的数据类型。
  通常以串的整体作为操作对象,如:在串中查找某个子串、求取一个子串、在串的某个位置上插入一个子串以及删除一个子串等。两个字符串相等的充要条件是:长度相等,并且各个对应位置上的字符都相等。设p、q是两个串,求q在p中首次出现的位置的运算叫做模式匹配。串的两种最基本的存储方式是顺序存储方式和链接存储方式。
相似回答