Invert "string"

Asked

Viewed 1,433 times

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 on printf, but does not print the string. Why?

Thank you.

2 answers

1

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

However, due to the numbers 5 and 4 in the code, this only works for strings of size 5. Any strings larger or smaller, this will go wrong. To solve this, you already have the strlen, then just use it to find the proper string size. Just replace 5 by the size of the string and 4 string size less 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 way out:

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

Ah, and note that it is necessary to explicitly put the null terminator (0) also in the aux.

See here working on ideone.

0

It is more elegant and functional that you create a variable and assign to it the value of 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 library string. h and stayed 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;
}

Browser other questions tagged

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