Invert a string correctly

Asked

Viewed 78 times

2

I cannot print the vector backwards, in this case, the word typed has to have exactly 6 letters. It follows the code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char nome[7],letra;
  int i,aux=0;

  printf("Digite uma palavra:");
  scanf("%s",nome);

  for(i=5;i>=0;i--){
    letra=nome[aux];//letra recebe o primeiro caractere do vetor
    nome[aux]=nome[i];//a primeira posiçao do vetor recebe o caractere da ultima
    nome[i]=letra;//a ultima posiçao recebe o caractere da primeira posiçao que foi armazenada na variavel letra
    aux++;//repetir o processo usando a segunda letra

  }
  printf("\n%s",nome);












    return 0;
}

2 answers

4


I don’t even think I need to manipulate the string, since it only asks to print reversed and not reverse the original, but I kept the change in the object because it may be that the statement may be wrong, if that is it should make a code even simpler.

This auxiliary variable only serves to cause confusion and the biggest problem is that it is reversing on both sides, so everything you are doing on one side is undoing the other, you have to do the operation up to half, which even makes it more efficient.

Note that I improved several other things.

#include <stdio.h>

int main() {
    char nome[7];
    printf("Digite uma palavra:");
    scanf("%6s", nome);
    for (int i = 0; i < 3; i++) {
        char letra = nome[i];
        nome[i] = nome[5 - i];
        nome[5 - i] = letra;
    }
    printf("\n%s", nome);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • The question was to reverse the position of the same characters and print the vector normally.I understood your code,!!

3

A classic example of this algorithm can be found in the famous book The C Programming Language (Chapter 3, page 55-56):

#include <string.h>

void inverter(char * s) {
    int c, i, j;
    for (i = 0, j = strlen(s)-1; i < j; i++, j--)
        c = s[i], s[i] = s[j], s[j] = c;
}

Integrating the function to your code, things would look something like this:

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

void inverter(char * s) {
    int c, i, j;
    for (i = 0, j = strlen(s)-1; i < j; i++, j--)
        c = s[i], s[i] = s[j], s[j] = c;
}

int main() {
    char nome[7];
    printf("Digite uma palavra: "); 
    scanf("%6s", nome);
    inverter(nome);
    printf("%s\n", nome);
    return 0;
}

See working on Repl.it

  • I didn’t know this "concatenation" of attributions using the comma. There is more material in the subject?

  • 1

    @Jeffersonquesado That’s called Comma Operator. The book quoted in the reply has a more detailed explanation on page 169.

Browser other questions tagged

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