Copying strings in C

Asked

Viewed 393 times

1

I would like a help on the following question:

I have a char with a text of 32 characters, so I would like to know how to separate this char in two of 16 characters.

Type:

char textao[32] = "Oi meu nome e Cesar tudo bem ai?"

And it has to stay:

char textoInicio[16] = "Oi meu nome e Ce"
char textoFim[16] = "sar tudo bem ai?"

I used strncpy(textoInicio, textao, 16) for the first part and it worked. Now I don’t know how to do for the second. I also didn’t want to use for.

Any hint?

1 answer

0


First of all, in C you always need additional space in your array because the strings need a null character (which can be represented with 0 or '\0') to indicate where they end up. And to copy a string from a point, just use the operator & to return the memory address of the specific location you want to copy.

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

int main()
{
    char textao[33] = "Oi meu nome e Cesar tudo bem ai?";
    char textoInicio[17];
    char textoFim[17];

    /*copiando texto*/
    strncpy(textoInicio, textao, 16);
    textoInicio[16] = 0;

    strncpy(textoFim, &textao[16], 16);
    textoFim[16] = 0;

    printf("inicio: %s\n", textoInicio);
    printf("Fim: %s", textoFim);

    getchar();
    return 0;
}
  • Thank you Ossetian_odin. It worked perfectly. D

Browser other questions tagged

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