Join strings : String Append « String « C / ANSI-C






Join strings


/*  Joining strings */
#include <stdio.h>
void main()
{
  char str1[40] = "To be or not to be";
  char str2[40] = ",that is the question";
  int count1 = 0;                /* Length of str1 */
  int count2 = 0;                /* Length of str2 */

  /* find the length of str1 */
  while (str1[count1] != '\0')   /* Increment count till we reach the terminating character*/
    count1++;                   
  
  /* Find the length of str2 */
  while (str2[count2] != '\0')  /* Count characters in second string      */
    count2++;
  
  /* Check that we have enough space for both strings  */
  if(sizeof str1 < count1 + count2 + 1)
    printf("\nYou can't put a quart into a pint pot.");
  else
  {  /* Copy 2nd string to end of the first  */
     count2 = 0;                 /* Reset index for str2 to 0   */
    while(str2[count2] != '\0')  /* Copy up to null from str2   */
      str1[count1++] = str2[count2++];

    str1[count1] = '\0';         /* Make sure we add terminator */
    printf("\n%s\n", str1 );     /* Output combined string      */
  }
}


           
       








Related examples in the same category

1.Demonstrates how to put strings together using strcat
2.Get first and last name and print them together
3.Join strings: revitalised: strlen and strcat
4.Append string to another string
5.Append string: strncatAppend string: strncat
6.String concatenate
7. Append substring to string: strncat
8. Append string: how to use strcat Append string: how to use strcat