Invert "string"

2

I have the following function:

void InverterString(char *str1){
    char aux[strlen(str1)];   

   for (int c=0; c<5; c++) aux[c] = str1[4 - c];

    printf("A string1 invertida fica: %s", aux);
}

However, it prints the phrase that is in printf , but does not print the string. Why?

Thank you.

    
asked by anonymous 24.08.2018 / 20:50

2 answers

1

For me, InverterString("abcde"); produced as edcba response. See here at ideone.

However, because of the numbers 5 and 4 in the code, this only works for strings of size 5. Any strings bigger or smaller, this will go wrong. To solve this, you already have strlen , so just use it to find the appropriate string size. Just replace 5 with string size and 4 with string length minus 1:

#include <stdio.h>

void InverterString(char *str1) {
    int tamanho = strlen(str1);
    char aux[tamanho + 1];

    for (int c = 0; c < tamanho; c++) {
        aux[c] = str1[tamanho - c - 1];
    }
    aux[tamanho] = 0;

    printf("A string1 invertida fica: %s", aux);
}

int main(void) {
    InverterString("O rato roeu a roupa do rei de Roma e a rainha roeu o resto.");
    return 0;
}

Here's the output:

A string1 invertida fica: .otser o ueor ahniar a e amoR ed ier od apuor a ueor otar O

Oh, and notice that you need to explicitly put the null terminator (0) also in aux .

See here working on ideone.

    
24.08.2018 / 20:58
0

It's more elegant and functional that you create a variable and assign it the size of your input string, so it will work for any string size. Also, trying to modify your code minimally, I made the change and included the string.h library and looked like this:

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

void InverterString(char *str1){
    int tamanho=strlen(str1);
    char aux[tamanho];   

    for (int c=0; c<tamanho; c++) aux[c] = str1[(tamanho-1)-c];

    printf("A string1 invertida fica: %s", aux);
}

int main(void) {
    InverterString("Olá Danny!");
    return 0;
}
    
25.08.2018 / 02:33