使用C语言
我已经将类似-> aaaabbbbbbccccc
的字符串压缩为a4b6c5
,现在我想将a4b6c5
解压缩为aaaabbbbbbccccc
。我已经尝试过,但无法执行此减压操作。请帮帮我。
#include<stdio.h>
void compress(char*stng);
int main(){
char stng[50000];
printf("Enter the String :");
scanf("%s",stng);
compress(stng);
return 0;
}
void compress(char*stng)
{
int i=0,count=0;
char c=stng[i];
while(stng[i]!='\0')
{
if(c==stng[i])
count++;
else
{
printf("%c%d",c,count); c=stng[i]; count=1;
}
i++;
}
printf("%c%d\n",c,count);
}
答案 0 :(得分:0)
#include <stdio.h>
void decompress(const char* code)
{
while(*code)
{
char c = *code++; // Get the letter to be repeated
int rep = 0;
while(isdigit(*code))
{
rep = rep*10 + *code++ - '0'; // Get the number of times to repeat the letter
}
char set[rep];
printf("%.*s", rep, memset(set, c, rep)); // Print letter [c], repeated [rep] times
}
}
int main(void)
{
char* code = "A4B5C6";
decompress(code);
return 0;
}
答案 1 :(得分:-1)
假设您永远不需要在字符串中嵌入数字,那么它将起作用。我只是将它用作旧字符串/新字符串,但是您可以对其进行调整,但是最适合您。
`
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char **argv[])
{
char szOldStr[] = "a5b11c6";
char szNewStr[128];
int iStrLen;
int iNumChars;
int iOldIndex;
int iNewIndex;
iStrLen = strlen(szOldStr);
iOldIndex = 0;
iNewIndex = 0;
while (szOldStr[iOldIndex])
{
// Look for a number, which would represent a compressed character
if (isdigit(szOldStr[iOldIndex]))
{
iNumChars = atoi(szOldStr + iOldIndex);
// Memset one less character, because we already moved one
// into the new string
memset(szNewStr + iNewIndex, szNewStr[iNewIndex - 1],
iNumChars - 1);
iNewIndex += iNumChars - 1;
// Advance past the number
while (isdigit(szOldStr[iOldIndex]))
++iOldIndex;
}
else
{
// Not a number, so just move the character to the new string
szNewStr[iNewIndex] = szOldStr[iOldIndex];
++iNewIndex;
++iOldIndex;
}
}
// Put a null at the end of our new string
szNewStr[iNewIndex] = '\0';
// Show what we created
puts(szNewStr);
}
`