stick
stick

Reputation: 88

Removing repeating letters from a given word

I am practicing strings, for the first time, and I am trying to remove consecutive repetitive letters from given words and print it. Say the word is committee, the out put will be comite.

My logic was to compare consecutive letters in the given word and store the letters into another string if they are not same.

When I compile and run my code I get weird symbols. What is the mistake in my code?

#include<stdio.h>
#include<string.h>
int main()
{
    char word[20],modword[20];
    int i=0,j=0;
    gets(word);
    for (i=0;i<20;i++)
    {
        if (word[i]!=word[i++])
        {
        modword[j]=word[i];
        j++;
        }

    }
    puts(modword);
    return 0;
}

Upvotes: 1

Views: 132

Answers (2)

MikeCAT
MikeCAT

Reputation: 75062

  • word[i]!=word[i++] invokes undefined behavior. It is intuitively explained as because whether of word[i] and word[i++] will be evaluated first is not specified and the evaluation order will change which element will be accessed.
  • Avoid using value of uninitialized variable having automatic storage duration, which is indeterminate, or you will invoke undefined behavior.

Try this:

#include<stdio.h>
#include<string.h>

#define MAX_LENGTH 20

int main(void)
{
    char word[MAX_LENGTH + 1],modword[MAX_LENGTH], *lf;
    int i=0,j=0;
    fgets(word, sizeof(word), stdin);
    if ((lf = strchr(word, '\n')) != NULL) *lf = '\0';
    for (i=0;i<MAX_LENGTH;i++)
    {
        if (i == 0 || word[i-1]!=word[i])
        {
            modword[j]=word[i];
            if (word[i] == '\0') break;
            j++;
        }

    }
    puts(modword);
    return 0;
}

Points:

  • Avoid using gets() to avoid buffer overrun.
  • Using magic numbers is not a good idea.
  • No increment of i in the loop. word[i-1] won't be evaluated when i == 0 thanks to short-circuit evaluation.
  • Stop the loop when terminating null-character is reached.

Upvotes: 3

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

You need to apply certain changes, e.g.

char word[20] = {0};
char modword[20] = {0};
int i = 0, j = 0;

fgets(name, sizeof(word), stdin);

for (i=0; i < sizeof(word) - 1;i++)
{
    if (word[i] != word[i+1])
    {
        modword[j] = word[i];
        j++;
    }

}

Upvotes: 0

Related Questions