Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation without strcat in C

Tags:

c

string

I am having trouble concatenating strings in C, without strcat library function. Here is my code

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

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';                
  printf("\n\n A: %s",a1);

  return 0;
}

I made corrections to the code. This is working. Now can I do it without strcpy?

like image 839
Vivek Avatar asked Dec 28 '22 03:12

Vivek


1 Answers

Old answer below


You can initialize a string with strcpy, like in your code, or directly when declaring the char array.

char a1[100] = "Vivek";

Other than that, you can do it char-by-char

a1[0] = 'V';
a1[1] = 'i';
// ...
a1[4] = 'k';
a1[5] = '\0';

Or you can write a few lines of code that replace strcpy and make them a function or use directly in your main function.


Old answer

You have

        0 1 2 3 4 5 6 7 8 9 ...
    a1 [V|i|v|e|k|0|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_]
    b1 [R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_|_|_|_|_|_]

and you want

        0 1 2 3 4 5 6 7 8 9 ...
    a1 [V|i|v|e|k|R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_]

so ...

a1[5] = 'R';
a1[6] = 'a';
// ...
a1[12] = 'l';
a1[13] = '\0';

but with loops and stuff, right? :D

Try this (remember to add missing bits)

for (aindex = 5; aindex < 14; aindex++) {
    a1[aindex] = b1[aindex - 5];
}

Now think about the 5 and 14 in the loop above.

What can you replace them with? When you answer this, you have solved the programming problem you have :)

like image 122
pmg Avatar answered Jan 08 '23 05:01

pmg