The approach is invalid. Consider a string like char str[] = "111";
.
So in these loops
for(i=0; i<n; i++)
{
for(j=i+1; j<n;j++)
{
if(str[i] == str[j])
{
str[j] = str[j+1];
}
}
}
str[0]
is equal tp '1'
. str[1]
is also equal to '1'
. So str[1]
is substituted for str[2]
that is also equal tp '1'
. As a result you will get that the array contains the string "11"
Moreover the inner loop processes not only adjacent repeated characters but all duplicated characters in the string.
Pay attention to that the function gets
is an unsafe function and is not supported by the C Standard any more. Use instead the standard function fgets
.
The program can look the following way
#include <stdio.h>
int main()
{
enum { N = 100 };
char str[N];
fgets( str, N, stdin );
for ( size_t i = 0, j = 0; str[i] != '\0'; )
{
if ( str[++i] != str[j] && str[i] != '\n' )
{
if ( i != ++j ) str[j] = str[i];
}
}
puts( str );
return 0;
}
If to enter the string "aapuroo"
then the program output will be
apuro
The subexpression str[i] != '\n'
used in the if statement is present because the function fgets
can append the new line character to the entered string. So this subexpression is used to exclude the new line character from the result string. Or you could before the loop to remove this character.