Posted By

charlieMonroe on 08/22/09


Tagged

c


Versions (?)

C


 / Published in: C
 

C

  1. /* Joining strings */
  2. #include <stdio.h>
  3. void main()
  4. {
  5. char str1[40] = "To be or not to be";
  6. char str2[40] = ",that is the question";
  7. int count1 = 0; /* Length of str1 */
  8. int count2 = 0; /* Length of str2 */
  9.  
  10. /* find the length of str1 */
  11. while (str1[count1] != '\0') /* Increment count till we reach the terminating character*/
  12. count1++;
  13.  
  14. /* Find the length of str2 */
  15. while (str2[count2] != '\0') /* Count characters in second string */
  16. count2++;
  17.  
  18. /* Check that we have enough space for both strings */
  19. if(sizeof str1 < count1 + count2 + 1)
  20. printf("\nYou can't put a quart into a pint pot.");
  21. else
  22. { /* Copy 2nd string to end of the first */
  23. count2 = 0; /* Reset index for str2 to 0 */
  24. while(str2[count2] != '\0') /* Copy up to null from str2 */
  25. str1[count1++] = str2[count2++];
  26.  
  27. str1[count1] = '\0'; /* Make sure we add terminator */
  28. printf("\n%s\n", str1 ); /* Output combined string */
  29. }
  30. }

Report this snippet  

You need to login to post a comment.