Home Forums C Programming help combining strings

Viewing 1 reply thread
  • Author
    Posts
    • #2151
      BlaineYIGz
      Participant

      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 1

      I 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…

      #include 
      #include

      void concat(char s1[], char s2[], maxlength);

      int main()
      {
      #define maxlength 101
      char s1[MAX];
      char s2 [MAX];

      printf("Enter the first string");
      gets(s1);
      printf("Enter the second string");
      gets(s2);
      printf("The combined string is:n",strcat(s1,s2));


      return 0;
      }

    • #3472
      GWILouisaxwzkla
      Participant

      Could try:


      #include
      #include
      #define MAX 101
      char * concat ( char s1[], char s2[], int maxlength );

      int main()
      {
      #define MAX 101
      char s1 [ MAX ];
      char s2 [ MAX ];

      printf("Enter the first string ");
      gets(s1);
      printf("Enter the second string ");
      gets(s2);
      printf("The combined string is: %s n", concat ( s1 , s2 , MAX ) );


      return 0;
      }

      char * concat ( char s1[], char s2[], int maxlength )
      {

      if ( strlen ( s1 ) + strlen ( s2 ) > maxlength )
      return s1;//stings too long , return first string as default
      strcat ( s1 , s2 ); //stick s2 to the back of s1
      return s1;
      }
Viewing 1 reply thread
  • The forum ‘C Programming’ is closed to new topics and replies.