Thursday, 11 September 2014

String concatenation in C Language using strcat & pointers – 2 programs with Example


String concatenation in C programming language using strcat & pointers. This is to concatenate the given input strings as one. It is a simple concatenation source code that generates the final output.

Here we have included the 2 example programs. They are,
  •     String concatenation using strcat,
  •     String concatenation using pointers
This C program is used to concatenate the two string values into the third string and print the value of string and combined two strings by using the strcat function & pointers. The header file is #include<string.h>. For example first value is ‘string’ and second value is ‘concatenation’ after strcat it will concatenate and stored in third value as ‘string concatenation’.

String concatenation codes:


1) C program for string concatenation using strcat function.

  1 //Header files
  2 #include <stdio.h>
  3 #include <string.h>
  4  
  5 int main()
  6 {
  7    //Program variable
  8    char b[50], c[50];
  9  
 10    printf("Enter the first value of string\n");//Display function
 11    gets(b);//Getting input function
 12  
 13    printf("Enter the second value of string\n");
 14    gets(b);
 15  
 16    strcat(b,c);//concatenation function
 17  
 18    printf("After string  concatenation is %s\n",b);
 19  
 20    return 0;
 21 }


2) Program in string concatenation using pointers

  1 //Header files
  2
  3 #include<stdio.h>
  4
  5 #include<conio.h>
  6
  7 char *xs(char*,char*);//Global variable
  8
  9 void main()
 10
 11 {
 12
 13 char *s4,*s5,*s6;//Program variable
 14
 15 clrscr();
 16
 17 puts("\t enter the first value of string:\n");
 18
 19 gets(s4);
 20
 21 puts("\t enter the second value of string:");
 22
 23 gets(s5);
 24
 25 s6=xs(s4,s5);
 26
 27 printf("after concatenation of string is %s",s6);
 28
 29 getch();
 30
 31 }
 32
 33 char *xs(char *s1,char *s2)
 34
 35 {
 36
 37     char *p=s1;
 38
 39     /*int j,h=0;
 40
 41     while(*(s1+h)!='\0')
 42
 43     {
 44
 45         h++;
 46
 47     }
 48
 49     j=h;
 50
 51     h=0;
 52
 53     while(*(s2+h)!='\0')
 54
 55     {
 56
 57         *(s1+j)=*(s2+h);
 58
 59         h++;
 60
 61         j++;
 62
 63     } */

 64
 65     while(*s1!='\0')
 66
 67         s2++;
 68
 69     while(*s1!='\0')
 70
 71     {
 72
 73         *s1=*s2;
 74
 75         s1++;
 76
 77         s2++;
 78
 79     }
 80
 81     *s4='\0';
 82
 83     //fs4--;
 84
 85     return (p);
 86
 87 }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.