-3

I need to insert a string in another string at a specific place. Here's a simple example:

char *a = "Dany S.";
char *b = "My name is  *a , I come from ...  ";

So, in string b in place of *a I expect to have Dany S.

How to do that ?

5
  • String literals can not be modified. Copy the content to array. Search for the string to be replaced. Show us what you have tried. Commented Aug 23, 2013 at 21:44
  • 1
    Ever heard of the C standard library? Commented Aug 23, 2013 at 21:44
  • 2
    I should really make you look through the standard library, it would do you good to have an idea what's in there, but I'll be nice and say snprintf. Commented Aug 23, 2013 at 21:45
  • *a is inside quote marks so it's just two characters; it does not refer to the variable. Moreover *a is the same as a[0] so it's only one character; just a 'D' Commented Aug 23, 2013 at 21:48
  • Inserting strings into another string in C Commented Jan 28, 2019 at 4:09

2 Answers 2

11

The best/easiest way would be to use standard C conventions:

char *a = "Dany S.";
char *b = "My name is %s, I come from...";

char *c = malloc(strlen(a) + strlen(b));

sprintf( c, b, a );

Then c contains your new string. When you're done with c, you will need to free the memory:

free( c );

If you want to use c in an output that terminates the line, then you can declare b as:

char *b = "My name is %s, I come from...\n";
Sign up to request clarification or add additional context in comments.

15 Comments

What about the end of line character?
Sizeof of the char* doesn't return the size of the string. Use strlen for that.
You still need the +1 for the null terminator.
+1 for ya cause you're a gentlemen.
IMHO it is useful to point out that after that malloc the OP is in charge to free that memory chunk pointed by c, otherwise he may leak memory (he seems to be a newbie).
|
2

You could use printf i.e.:

#include <stdio.h>
char *a = "Dany S.";
char *b = "My name is  %s , I come from ...  ";

printf(b, a);

3 Comments

Isn't it sprintf instead?
There is the whole family, printf outputs to stdout, fprintf(file, to a file, sprintf to a string then there are the v.. versions without knowing more about what is required ...
The question is not how to print something on screen but to " insert a string in another string".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.