Transform and return a centered string s into a length width string

Asked

Viewed 44 times

0

In this exercise I must pass to the function a string, a size and the character I want to include in the string, but I find problems when executing it, the string that should be centered ends up being filled by the asterisks.

//Como deveria ficar:  asteristicos Apresentando os dados asteristicos 

/*Transforma e devolve a string s centralizada em uma string
de comprimento width. O preenchimento é feito usando o
caractere especificado por fillchar. A string original
é devolvida se width for menor ou igual a strlen(s).*/

char * redefine(char * s, int width, char fillchar){
    int i;
    char aux;
    
    for(i = 0; i < 46 ; i++){
        aux = s[i];
        s[i] = fillchar;
    }
    
    printf("%s\n", s); //Teste para ver ser a string esta correta.
}   

int main(){
    char str2[81] = "Apresentando os dados";

    // forma usada como teste.
    redefine(str2, 80, '*')
    // assim é a chamada da função printf("\"%s\"\n", redefine(str2, 80, '*'));

    return 0;
}

1 answer

0


First you need to calculate how many positions you have to fill. Fill in half copy the string and fill in the remaining positions.

#include <stdio.h>
#include <string.h>
char * redefine(char * s, int width, char fillchar){
    int i, n;
    char aux[width];
    if (strlen(s) >= width)
        return s;
    n = (width - strlen(s)) / 2;
    for(i = 0; i < n ; i++){
        aux[i] = fillchar;
    }
    aux[i] = '\0';
    strcat(aux, s);
    for (i=strlen(aux); i<width-1; i++) {
        aux[i] = fillchar;
    }
    aux[width-1] = '\0';
    strcpy(s, aux);
    return s;
}   

int main(){
    char str2[81] = "Apresentando os dados";
    printf("\n[%s]\n", redefine(str2, 80, '*'));

    return 0;
}

Browser other questions tagged

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