0

Is there any function/common method for concatenation between two string, while string2 appears in string1 in a specified place?

If the question was not clear enough, take a look at this example:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[100] = "I love Gyros";

    concatenate(&str[2], "dont ");

    printf(str);

    return 0;
}

Output:

I dont love Gyros
Alan Salios
  • 241
  • 2
  • 9

2 Answers2

4

Is there any function/common method for concatenation between two string, while string2 appears in string1 in a specified place?

No, there isn't.

You can accomplish what you are trying using many approaches. One approach would be to use sprintf.

char str[100];
sprintf(str,"I %s love Gyros", "don't");

Another approach would be to shift the contents of str to the right by the amount you need, and then set the values of the intermediate elements.

#include <stdio.h>
#include <string.h>

void insertInString(char* str1, size_t pos, char const* str2)
{
   size_t len1 = strlen(str1);
   size_t len2 = strlen(str2);
   size_t i = 0;

   // Shift the contents of str1
   for ( i = len1; i >= pos; --i )
   {
      str1[i+len2] = str1[i];
   }

   // Now place the contents of str2 starting from pos
   for ( i = 0; i < len2; ++i )
   {
      str1[i+pos] = str2[i];
   }
}

int main()
{
    char str[100] = "I love Gyros";
    insertInString(str, 2, "don't ");
    printf("%s\n", str);
    return 0;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

There are no functions to do what you want. Rather than having function concatenate which for it to work well is non trivial, have function insert_phrase with prototype... char *insert_phrase(char *string,char *phrase,size_t after_word); Your example would now read...

Insert_phrase(str,"don't ",1);

Your concatenate function to be of any real use would need to do lexical analysis on both arguments before inserting don't into str.

phil
  • 561
  • 3
  • 10