0
I am implementing this code in order to receive two strings and compare them, if the two strings are different I concatenate the two into one vector, but I want to add a blank in them.
How can I perform this task without using the string library. h?
Follows the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j, k;
char aux;
char nome[10];
char sobreNome[10];
char concatNome[20];
printf("Digite o seu primeiro nome: \n");
gets(nome);
printf("Digite o seu sobrenome: \n");
gets(sobreNome);
/*Este for compara os valores(caracteres) índice por
índice e avalia se o tamanho dos vetores nome e
sobrenome são iguais.*/
for(i=0; nome[i]==sobreNome[i] && nome[i]!= '\0' &&
sobreNome[i]!= '\0' && i<sizeof(nome) &&
i<sizeof(sobreNome); i++);
if(nome[i]=='\0' && sobreNome[i]=='\0'){
printf("Os nomes são iguais\n");
}else{
/*Este for copia a string armazenada no vetor nome
e armazena no vetor concatNome*/
for(j=0;j<sizeof(concatNome)&&nome[j]!='\0'; j++){
aux = nome[j];
concatNome[j] = aux;
}
/*Esse for é responsável por concatenar a string do vetor sobreNome ao
vetor concatNome*/
for(k=0;j<sizeof(concatNome)&&sobreNome[k]!='\0'
&&concatNome[j]!='\0';k++, j++){
aux = sobreNome[k];
concatNome[j] = aux;
}
concatNome[j]='\0';
printf("Nome e sobrenome concatenados : %s\n", concatNome);
}
return 0;
}
Ola Kelion, welcome to stackoverflow. : ) Could you please add comments to your code, explaining in each part, what is he doing? In particular, what each of the 3 commands
for
do. This will help you better understand your code, and make it easier to explain to you the answer to what you are asking for. ^_^– msb
Note that you have set your strings to a fixed size and therefore the sizeof operator will return the amount of bytes allocated, 10 for name and surname and 20 for concatName which, it seems to me, is not what you are expecting in your loops, unless you always provide names and surnames with exactly 10 characters, but in this case you will be overtaking the leased area as the terminator character ' 0' will be automatically inserted. Tip: work considering only the ending character ' 0 to control the copying of characters.
– anonimo