I’m having a problem running a repeat on C

Asked

Viewed 48 times

0

Description of the issue: "Implement the function below that takes a string and compresses it into a single character, any set of consecutive repeated characters."

function:
char *strpack(char *s)

Example of how it should work:

    strpack("Arrecadddaccao")           --> "Arecadacao"
    strpack("   AAAaaaBBB   CCCIALFFA") --> " AaB CIALFA""*

I implemented the function below:

char *strpack(char *s)
{
    int i = 0, j = 0, tam = strlen(s);
//Analisa caractere por caractere
    for(i = 0; i <= tam; i = j)
    {
//Analisa a quantidade de caracteres repetidos
        for(j = i; j <= tam; j++)
        {
            if(s[i] != s[j])
            {
//Elimina os caracteres repetidos
                s[++i] = s[j];
                break;
            }
        }
    }
    return s;

Mas, por algum motivo, a repetição só é executada uma vez. Não consegui identificar o erro.
Qualquer contribuição é bem-vinda.

1 answer

0

Good afternoon.

The repeat is only performed once because of the break within the if. I removed it here and it worked perfectly.

Since you are working by passing by reference then you do not need to return the string in its function, because you already change its content. This occurs because in the passage by reference we pass the address of the variable/vector and not a copy of it and so every change made is in the variable/vector that we pass as arguments. So you can leave void in return.

If you don’t like to return void in its functions then you can do a size validation on your string, that is, if the string is size 0 then return -1, otherwise return 0. It would look like this:

int strpack(char *s)
{
    int i = 0, j = 0, tam = strlen(s);
    if(tam == 0) return -1;
    //Analisa caractere por caractere
    for(i = 0; i <= tam; i = j)
    {
    //Analisa a quantidade de caracteres repetidos
        for(j = i; j <= tam; j++)
        {
            if(s[i] != s[j])
            {
                //Elimina os caracteres repetidos
                s[++i] = s[j];
                //break;
            }
        }
    }
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.