Problem splitting a String array into C

Asked

Viewed 186 times

0

I’m making a program that needs you to find half a string vector, but that half cannot cut any word, so that half would necessarily have to be the next space found after half. Soon after finding this half the program must divide the vector into 2 string vectors. One with the first part and the other with the second.

So far what I have is this:

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

void DivideString(char *Texto, char *Metade1, char *Metade2, int tamanho,int 
metade){
int i;
for(i = 0; i < metade; i++){
    Metade1[i] = Texto[i];
}
for(i=metade; i<tamanho; i++){
    Metade2[i] = Texto[i];
}
}

int CalculaMeio(int metade, char *Texto){
while(Texto[metade]!=' '){
    metade++;
}
return metade;
}

int main(){
char *Texto, *Metade1, *Metade2;
int i;

Texto = (char*)malloc(1000*sizeof(char));

Texto = "Testando como funcionam strings em c para trabalho";

int tamanho = strlen(Texto), metade = tamanho/2;

printf("tamanho: %d  metade: %d\n",tamanho, metade);

metade = CalculaMeio(metade, Texto);

printf("nova metade: %d\n",metade );

Metade1=(char*)malloc(metade*sizeof(char));
Metade2=(char*)malloc((tamanho-metade)*sizeof(char));

DivideString(Texto, Metade1, Metade2, tamanho, metade);

printf("%s\n",Metade1 );
printf("%s\n",Metade2 );
return 0;
}

When executing this program you have the following:

Aparantemente dando erro por não estar printando a segunda parte da frase

As in the image, the program prints the first vector correctly but the second vector is not printed.

Would that be some problem with the buffer?

  • And if the string has no spaces ?

  • It would always present spaces. It is to divide a normal text, with spaces with more than 1 word... Same as the program

1 answer

2


Its function DivideString() can be implemented in a much simpler way, see:

#include <ctype.h>
#include <string.h>

void DivideString( const char * txt, char * m1, char * m2 )
{
    int tam = strlen(txt);
    int meio = tam / 2;

    while( txt[meio] && !isspace(txt[meio]) )
        meio++;

    *m1 = '\0';
    *m2 = '\0';

    strncat( m1, txt, meio );
    strncat( m2, txt + meio + 1, tam - meio );
}

Testing:

#include <stdio.h>

int main( void )
{
    char texto[] = "O rato roeu a roupa do rei de Roma.";

    char metade1[100];
    char metade2[100];

    DivideString( texto, metade1, metade2 );

    printf( "Texto: %s (Tamanho: %ld)\n", texto, strlen(texto) );
    printf( "Metade1: %s (Tamanho: %ld)\n", metade1, strlen(metade1) );
    printf( "Metade2: %s (Tamanho: %ld)\n", metade2, strlen(metade2) );

    return 0;
}

Exit:

Texto: O rato roeu a roupa do rei de Roma. (Tamanho: 35)
Metade1: O rato roeu a roupa (Tamanho: 19)
Metade2: do rei de Roma. (Tamanho: 15)

See working from Ideone.com

  • Thank you so much :) It worked well here

Browser other questions tagged

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