//C program to remove consecutive repeated characters from string.
//C program to remove consecutive repeated elements from an array.
#include <stdio.h>
#include<string.h>
int main()
{
int i,j,len,len1;
char str[100];
printf("Enter a string with repeated adjacent characters:");
gets(str);
len=strlen(str);
//assign 0 to len1 - length of removed characters
len1=0;
//Removing consecutive repeated characters from string
for(i=0; i<(len-len1);)
{
if(str[i]==str[i+1])
{
//shift all characters
for(j=i;j<(len-len1);j++)
str[j]=str[j+1];
len1++;
}
else
{
i++;
}
}
printf("String after removing duplicate adjacent elements : %s\n",str);
return 0;
}
/*
Enter a string with repeated adjacent characters:abbcccdefabc
String after removing duplicate adjacent elements : abcdefabc
*/
//Removing consecutive members in an array
#include<iostream>
using namespace std;
class Base
{
};
void print(int* p)
{
while(*p)
cout<<*p++<<" ";
cout<<endl;
};
int main()
{
cout<<""<<endl;
int arr[]={1,2,2,3,3,2,4,5,5,55,555,5};
print(arr);
int size=sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;)
{
if(arr[j]==arr[j+1])
{
for(int k=j;k<size;k++)
{
arr[k]=arr[k+1];
}
//shift
size--;
}
else
{
//check next
j++;
}
}
}
print(arr);
return 0;
}
/*
1 2 2 3 3 2 4 5 5 55 555 5
1 2 3 2 4 5 55 555 5
*/
No comments:
Post a Comment