Concatenate n characters of a typed word

Asked

Viewed 58 times

0

I want to make a program in which the user type any word and is stored in a string, soon after it is necessary to store that same word in another string only in the reverse form, for example if it was typed "BRAZIL" I want to return "LISARB". I was able to invert the character positions, however I cannot concatenate the characters so that they are displayed in one line.

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

main()
{
char p[100], c, invertida;
int tam ,i;

printf ("\n Digite uma palavra: ");
gets (p);
tam = strlen(p);

for (i=tam -1 ; i>=0; i--)
{
    c = p[i];
    strcat (c,p[i]);
}
printf("\n %s", c);
}
  • That line, p[i] = p[i], doesn’t seem quite right or make sense. I could review the code you posted in the question?

2 answers

0


A simple method of you doing this is like this:

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

main()
{
    char p[100], c, invertida[100];
    int tam, i;

    printf ("\n Digite uma palavra: ");
    gets (p);
    tam = strlen(p);

    int count = 0;
    for (i=tam -1 ; i>=0; i--)
    {
        invertida[count] = p[i];
        count += 1;
    }
    // Finaliza String
    invertida[count] = '\0';
    printf("\n %s", invertida);
}

While traversing the string otherwise you add a counter to put the value in the inverted string.

0

You can user a C function responsible for reversing the characters, called strrev().

strrev

char *strrev(char *str);

Browser other questions tagged

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