How to invert a character array in C?

Asked

Viewed 1,522 times

-1

I have to invert a vector, example: ola = Alo.

#include<stdio.h>
#include<string.h>
#include<bits/stdc++.h>
int main()
{
    char c[5];
    scanf("%s" ,c);
    for(int i=5; i>=-1;i--)
    printf("%s" ,c[i]); 
    return 0;
}
  • You walk the string whole and exhibited herself print("%s", c) every iteration. You should not display one character at a time?

  • print("%s", c[i]) tbm n works

  • Because %s expects a string and you are passing only one. Try to read and understand what each part of the code you are writing does.

  • printf("%c" ,c[i]); used %c it returns the correct result but before a "?"

  • return:12345 54321

  • but comes back with a special character similar to a translation

  • for(int i=strlen(c);i;)putchar(c[--i]);

  • Remember that in a string in C you need to predict the space for the terminator ' 0'. If you want to store 5 characters declare char c[6]; (indexes from 0 to 5). To print backwards: is (i=5; i>=0; i--) printf("%c", c[i]);

Show 3 more comments

1 answer

0

If you want to invert the array and not just write its inverted values you must create another variable. One way to do it is like this:

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

int main()
{
    char c[10];
    char invertida[10];

    scanf("%s", c);
    // strlen() retorna o tamanho da string
    // for soma o j e percorre c invertido
    int j = 0;
    for(int i=strlen(c)-1; i>=0;i--) {
        invertida[j] = c[i];
        j += 1;
    }
    // Finaliza String
    invertida[j] = '\0';

    printf("%s", invertida); 
    return 0;
}

Browser other questions tagged

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