Home › Forums › C Programming › help combining strings
- This topic has 1 reply, 2 voices, and was last updated 16 years, 1 month ago by GWILouisaxwzkla.
- AuthorPosts
- November 3, 2008 at 11:49 pm #2151BlaineYIGzParticipant
Hi, I’m a total newbie at this. I’m really struggling here. any help would be awsome!
the instructions are: Include the string library functions strlen(), strcat(), and strncat() within a function having the prototype concat(char string1[], char string2[], int maxlength)Here is what I need to do:
read in string 1
read in string 2
pass both strings to the concat function
Once I am in the function, I need to get the length of both strings.
if the length of string1 + the length of string 2 is greater than the maximum number of characters allowed
use strncat and limit the number of characters copied to maximumnumber – length of string 1
otherwise use strcat and copy all of string 2 into string 1I could use some help with the code. Not sure what I’m doing and again, any help would be great. thanks
what I have so far is…123456789101112131415161718192021#include <stdio.h><br />#include <string.h><br /><br />void concat(char s1[], char s2[], maxlength);<br /><br />int main()<br />{<br />#define maxlength 101<br />char s1[MAX];<br />char s2 [MAX];<br /><br />printf("Enter the first string");<br />gets(s1);<br />printf("Enter the second string");<br />gets(s2);<br />printf("The combined string is:n",strcat(s1,s2));<br /><br /><br />return 0;<br />}<br /> - November 6, 2008 at 5:03 pm #3472GWILouisaxwzklaParticipant
Could try:
123456789101112131415161718192021222324252627282930<br />#include <br />#include <br />#define MAX 101<br />char * concat ( char s1[], char s2[], int maxlength );<br /><br />int main()<br />{<br />#define MAX 101<br />char s1 [ MAX ];<br />char s2 [ MAX ];<br /><br />printf("Enter the first string ");<br />gets(s1);<br />printf("Enter the second string ");<br />gets(s2);<br />printf("The combined string is: %s n", concat ( s1 , s2 , MAX ) );<br /><br /><br />return 0;<br />}<br /><br />char * concat ( char s1[], char s2[], int maxlength )<br />{<br /><br />if ( strlen ( s1 ) + strlen ( s2 ) > maxlength )<br />return s1;//stings too long , return first string as default<br />strcat ( s1 , s2 ); //stick s2 to the back of s1<br />return s1;<br />}
- AuthorPosts
- The forum ‘C Programming’ is closed to new topics and replies.