Good afternoon people, I have this doubt. How do I concatenate two strings without using function or library for this?
Good afternoon people, I have this doubt. How do I concatenate two strings without using function or library for this?
You create a new string of sufficient size and copy the characters of the two strings into the new one. Size is the sum of the sizes of the other two strings. The copy of each string can be done with for
for each.
That is:
char a[] = "teste1";
char b[] = "teste2";
int tamanho1 = 0;
while (a[tamanho1]) tamanho1++;
int tamanho2 = 0;
while (b[tamanho2]) tamanho2++;
int tamanho3 = tamanho1 + tamanho2 + 1;
char *c = (char *) malloc(tamanho3);
for (int i = 0; a[i]; i++) {
c[i] = a[i];
}
for (int i = 0; b[i]; i++) {
c[i + tamanho1] = b[i];
}
c[tamanho1 + tamanho2] = 0;
However, I do not recommend doing this. The tendency in doing this is to reinvent the wheel multiple times, which is unnecessary, confusing and very prone to errors. The strlen
function replaces these two while
s. The strcat
function could be used to eliminate for
s.
There are several ways to do string concatenation. Here are some examples that are more practical and less costly.
char * str1 = "Teste1";
char * str1 = "Teste2";
char str3[50];
/* Exemplo 1 */
memcpy(str3, str1, 6);
memcpy(str3[6], str2, 6); // str3: "Teste1Teste2"
/* Exemplo 2 */
memcpy(str3, str1, 6);
memcpy(str3[6], "", 1);
memcpy(str3[7], str2, 6); // str3: "Teste1 Teste2"
You can iterate through the array of characters in the second string and add one by one to the end of the first string.
char str1[100], str2[100], i, j;
//Conta o tamanho da primeira string (poderia usar strlen) - char str1[100], str2[100], i, j;
//Conta o tamanho da primeira string (poderia usar strlen) - %pre% é o fim da string
for(i=0; str1[i]!='%pre%'; ++i);
// O segundo loop concatena cada caracter da segunda string ao fim da primeira.
// Teste antes para não estourar o tamanho máximo da primeira.
for(j=0; str2[j]!='%pre%'; ++j, ++i) {
str1[i]=str2[j];
}
str1[i]='%pre%';
é o fim da string
for(i=0; str1[i]!='%pre%'; ++i);
// O segundo loop concatena cada caracter da segunda string ao fim da primeira.
// Teste antes para não estourar o tamanho máximo da primeira.
for(j=0; str2[j]!='%pre%'; ++j, ++i) {
str1[i]=str2[j];
}
str1[i]='%pre%';
I do not know why you would use something like this, since you would have to implement all the controls again, but that's it.