Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include<iostream>

#include<string.h>
using namespace std;
char b[100];
static int noof_times=1,index=0;

char compress(char *a,char c,int p,int ,int )


{
if(p==-1)return c;
char t=compress(a,a[p],p-1,index,noof_times);
if(t==c)noof_times++;
else
{
a[index++]=t;
a[index++]=noof_times+48;
noof_times=1;
}
return c;
}

int main()
{
cout<<"enter the String ;";
cin.getline(b,100);
int p=strlen(b)-1;
char c=compress(b,b[p],p-1,index,noof_times);
if(noof_times>1)
{
b[index++]=b[p];
b[index++]=noof_times+48;
}
b[index]='\0';
cout<<b;
}
----------------------------------------------------------------------
public class Trystring {

/**
* @param args
*/
public static void main(String[] args) {

String str= "aaaabbcccc";


StringBuffer str1 = new StringBuffer(str);
System.out.println("Input string is "+str1);
char prev = str1.charAt(0);
char curr;
int count=1,prev_index=0;
for(int i=1;i<str1.length();i++)
{
curr= str1.charAt(i);
if(prev==curr)
count++;
else
{
if(count>2)
{
int offset= prev_index+count;
str1.delete(prev_index+1,offset);
str1.insert(prev_index+1, count);
count=1;
prev = curr;
prev_index = prev_index+2;
i=prev_index;
}
else
{
str1.deleteCharAt(prev_index+1);
str1.insert(prev_index+1, count);
count=1;
prev=curr;
prev_index=prev_index+2;
}
}
if(i==(str1.length()-1))
{

int offset= prev_index+count;


str1.delete(prev_index+1,offset);
str1.insert(prev_index+1, count);

}
}
System.out.println("Output string is " +str1);
}
}

You might also like